ajax post data null in mvc3 controller method

2019-08-05 00:25发布

问题:

One of my jquery ajax posts sends post data to my .NET MVC3 controller method, but at the controller method, the data shows up as null. I have many other ajax posts that use practically the same method body, and they all work fine, so I'm not sure what is happening.

Ajax post:

$.ajax({
    url: '/Entity/Relate',
    type: 'POST',
    dataType: 'json',
    contentType: 'applicaiton/json; charset=utf-8',
    data: { primaryEntityId: parseInt(entityParentId, 10), relatedEntityId: _createdId },
    success: function (data)
    {
        //do stuff
    },
    error: function ()
    {
        // throw error
    },
    complete: function ()
    {
        //do more stuff
    }
});

Controller method:

[HttpPost]
public int Relate(int primaryEntityId, int relatedEntityId)
{
    return relationshipRepository.Add(primaryEntityId, relatedEntityId);
}

The problem is when I break on the Relate method, primaryEntityId and relatedEntityId are null, even though in the post data in Firebug, it shows that {primaryEntityId: 13, relatedEntityId: 486} have been posted to the method.

Any suggestions or ideas as to why the post looks good, but the controller isn't picking up the data?

回答1:

but at the controller method, the data shows up as null

That's not possible because Int32 is a value type and value types in .NET cannot be null. You probably meant that they are assigned to the default value. Anyway.

The problem is related to the contentType parameter that you have set in your AJAX request. You need to remove it because you are not sending JSON but a standard application/x-www-form-urlencoded request:

$.ajax({
    url: '/Entity/Relate',
    type: 'POST',
    dataType: 'json',
    data: { 
        primaryEntityId: parseInt(entityParentId, 10), 
        relatedEntityId: _createdId 
    },
    success: function (data)
    {
        //do stuff
    },
    error: function ()
    {
        // throw error
    },
    complete: function ()
    {
        //do more stuff
    }
});

If you want to send a JSON request define a view model:

public class RelateViewModel
{
    public int PrimaryEntityId { get; set; }
    public int RelatedEntityId { get; set; }
}

then have your controller take this view model as argument:

[HttpPost]
public int Relate(RelateViewModel model)
{
    return relationshipRepository.Add(model.PrimaryEntityId, model.RelatedEntityId);
}

and finally send a real JSON request (using the JSON.stringify method):

$.ajax({
    url: '/Entity/Relate',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json;charset=utf-8',
    data: JSON.stringify({ 
        primaryEntityId: parseInt(entityParentId, 10), 
        relatedEntityId: _createdId 
    }),
    success: function (data)
    {
        //do stuff
    },
    error: function ()
    {
        // throw error
    },
    complete: function ()
    {
        //do more stuff
    }
});