Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC 3 JSON Model Binding not working

I am using MVC3 and that i know MVC3 support binding JSON literal to Action parameter. But i can't do it successfully;

I have a class name Tag

public class Tag
{
    public int tagId { get; set; }
    public string tagName { get; set; }
}

An Action on controller called Tag

    [HttpPost]
    public ActionResult Tag(Tag tag)
    {
        // Here will be codes...
        return Json(new { success = 0 });
    }

Javascript code that send js object as JSON to my action

    var tag ={tagId:5,tagName:"hello"};
    $.ajax({
           url: "/image/tag",
           type: "POST",
           data: $.toJSON(tag),
           success: function (r) {
               if (r.success == 1) {
                   window.location = r.redirect;
               }
           }

Post Data that I see in Firebug Net tab

{"tagId":5,"tagName":"hello"}

Parameter name tag in Tag Action is not null but has values O for tagId and null for tagName. What the problem in here?

like image 635
Yucel Avatar asked Feb 13 '12 12:02

Yucel


1 Answers

You need to set the content type of the request to application/json:

$.ajax({
    url: '/image/tag',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: $.toJSON(tag),
    success: function (r) {
        if (r.success == 1) {
            window.location.href = r.redirect;
        }
    }
});

Ah, and you don't need to have your Tag model properties start with a lowercase letter:

public class Tag
{
    public int TagId { get; set; }
    public string TagName { get; set; }
}

Remark 1: The JavaScriptSerializer class that ASP.NET MVC 3 uses behind the scenes is capable of properly handling this.

Remark 2: In your Tag action you seem to be returning the following JSON: {"success":0} whereas in your success AJAX callback you seem to be using some r.redirect property which doesn't exist.

Remark 3: Avoid naming your controller actions the same way as your view models. Normally action names should represent verbs (like List, Save, Delete, ...) whereas view models represent resources (TagModel, ...).

like image 75
Darin Dimitrov Avatar answered Nov 21 '22 15:11

Darin Dimitrov