1

I am having trouble to pass the serialized js object to controller and let the default model binder automtatically deserialize it into my object.

I can manually deserialize the value into my object, it's all fine. but I would like to know why it doesn't work.

Thanks

Here is my code snippet

js code

$.post('/Order/AddRecordAddHocStock2', { idPatient: $patientId, "orderItems": JSON.stringify($orderItems) }, function (data) {
                //$("#recordingdialog").html(data).dialog("open");

                var $dialog = $("#popup_dialog2");

                $dialog.empty();
                $dialog
                .dialog({
                    bgiframe: true,
                    title: $title,
                    height: 700,
                    width: 650,
                    modal: true,
                    autoOpen: false,
                    resizable: false
                });

                $dialog.html(data).dialog("open");

            });

Here is the post value get it from firefox

idPatient   72
orderItems     [{"Id":0,"ProductName":"01870","Quantity":0,"StockOnHand":0,"MaxAllowance":12,"OrderTotal":0},{"Id":0,"ProductName":"01870","Quantity":0,"StockOnHand":0,"MaxAllowance":1,"OrderTotal":0}]

Here is my controller which I expected the orderItems should be automatically populate the value from the previous js object

        [HttpPost]
    public virtual ActionResult AddRecordAddHocStock2(long idPatient, List<OrderItemModel> orderItems)
    {
       var items = Request.Form["orderItems"];
       //it's working if I manually deserialize the js object
       var data = new   JavaScriptSerializer().Deserialize(items,typeof(List<OrderItemModel>));
    }

1 Answer 1

4

You need to set the content-type to "application/json". See this blog post for more details. Focus on the jQuery code sample, not the server side changes which are unnecessary in ASP.NET MVC 3: http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

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

3 Comments

jquery $.post does not support content-type. I tried with $.ajax, it works, but I now have another problem, when I get the data back, the jquery raise parseerror. the status is 200, but statstext shows error
You'll probably need to post more information about the new error. Perhaps a new question with more details. Is there a server exception being thrown? What does Fiddler show as the response? Etc.
Hi Haacked I solved the problem. I had another issue with the date querystring, the default model binder can't bind it to my controller's parameter. my date format looks like dd/MM/yyyy

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.