2

I am creating a JSON string in my JavaScript and sending it to my controller in mvc application. My code which create JSON string :

     $('#btnassign').click(function () {

            var arrPrice = "";
            var arrMarkUP = "";

            $("table tr").each(function () {

                if ($(this).find('input:checkbox:first').is(':checked')) {

                    if ($(this).find('input.inputprice').val() != "") {
                        arrPrice += "{";
                        var price = $(this).find('input.inputprice').val();
                        var id = $(this).find('input[type=hidden]').val();
                        arrPrice += '"Id":"' + id + '","Price":"' + price + '"';
                        arrPrice += "},";
                    }
                    if ($(this).find('input.inputmarkup').val() != "") {
                        arrMarkUP += "{";
                        var price = $(this).find('input.inputmarkup').val();
                        var id = $(this).find('input[type=hidden]').val();
                        arrMarkUP += "Id:" + id + ",Price:" + price;
                        arrMarkUP += "},";
                    }
                }
            });

            var lastindexp = arrPrice.lastIndexOf(",");
            arrPrice = arrPrice.substring(0, lastindexp) + "|";
            var lastindexm = arrMarkUP.lastIndexOf(",");
            arrMarkUP = arrMarkUP.substring(0, lastindexm) + "|";
            alert(arrPrice);
            alert(arrMarkUP);

            $("#hdPrice").val(arrPrice);
            $("#hdMarkUP").val(arrMarkUP);

            $("#AssignProductForm").submit();
        });

    });

My JSON string generates from above code :

    {"Id":"1","Price":"4"},{"Id":"2","Price":"6"}

My Controller parsing code :

    [HttpPost]
    public ActionResult AddProducts(FormCollection collection, string txtsearch)
    {
        var ManualPricing = collection["hdPrice"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

         JavaScriptSerializer ser = new JavaScriptSerializer();
         var Manual = ser.Deserialize<PriceMargin>(ManualPricing[0]);         
    }

Price margin is a class to which it should deserialize :

    public class PriceMargin
    {
        public string Id { get; set; }
        public string Price { get; set; }
    }

Line var Manual = ser.Deserialize<PriceMargin>(ManualPricing[0]) gives me an error:

Invalid JSON primitive: {"Id":"2","Price":"9"}.

Solution:

var list = new JavaScriptSerializer().Deserialize<List<KeyValue>>(json);

public class KeyValue
{
   public string key;
   public string value;
}
3
  • 3
    Why are you manually building the string? You can use native datatypes and then encode those datatypes to JSON strong and decode the JSON string to native datatypes Commented Jul 7, 2013 at 16:34
  • i don't know how to do it , i am new to javascript , jquery !! any example ? Commented Jul 7, 2013 at 16:36
  • added example on using javascript objects Commented Jul 7, 2013 at 16:41

3 Answers 3

1

Your JSON is invalid.

JSON can only have a single root object.

If you want to have multiple objects, serialize an array.

Sign up to request clarification or add additional context in comments.

Comments

1

To follow up the comment, if you want an array of objects to you could do something like:

pricesArray = [];
$("table tr").each(function () {
  if ($(this).find('input:checkbox:first').is(':checked')) {
    var price = $(this).find('input.inputprice').val();
    var id = $(this).find('input[type=hidden]').val();
    pricesArray.push({Id : id, Price: price});
  }
});
// pricesArray [{"Id":"1","Price":"4"},{"Id":"2","Price":"6"}]

pricesArray should now contain the data you want, it should be much easier to serialze and desearilze your data and send it around now

Comments

0

Last time I encountered that error, I tried to pass an object value direct to the json data... i.e

data = { datavalue: @Object.valueField};

in Json

$.ajax({
    type: "POST",
    url: "/Controller/FunctionToPostTo",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (response) {
        alert('Success');
    },
    failure: function (response) {
        alert('Failure');
        alert(response.responseText);
    },
    error: function (response) {
        alert('Error');
        alert(response.responseText);
    }
});

to solve the problem I created a separate variable and assigned the value to it, passing the data value in Ajax I used the JSON.stringify function

var variableHolder = @Object.valueField;
data = { datavalue: variableHolder };

in Json

$.ajax({
    type: "POST",
    url: "/Controller/FunctionToPostTo",
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (response) {
        alert('Success');
    },
    failure: function (response) {
        alert('Failure');
        alert(response.responseText);
    },
    error: function (response) {
        alert('Error');
        alert(response.responseText);
    }
});

Then the problem dissapeared

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.