Tarynn
Tarynn

Reputation: 469

Difficulty binding mvc model to JSON post

I have the following JSON Request body (copied from ie10 Admin Panel Network capture)

{"FirstName":"James","LastName":"Jones","Email":"[email protected]"}

My controller is as follows (the x variable is to break on):

[HttpPost]
public void EditPerson(PersonUpdateViewModel person)
{
    int x = 0;
}

My ViewModel is as follows:

public class PersonUpdateViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

The EditPerson Action is reached, I break on the x variable, but all of the properties in the person variable are null, does anyone have any hints for what I might be doing wrong? At this point I would even be ok accepting the raw JSON string and parsing from there but I can't get any parameter into the action method.

javascript function I am posting from by request:

var submitEdit2 = function () {
    var editables = $('.editable')
    var person = new Object();
    for (var i = 0; i < editables.length; i++) {
        var editable = editables[i];
        person[editable.name] = editable.value;
    }
    var jform = JSON.stringify(person);
    $.post('/Person/EditPerson', jform, null, 'json');
}

Upvotes: 2

Views: 270

Answers (1)

brianc
brianc

Reputation: 475

Try using an AJAX post and specifying the
contentType to 'application/json; charset=utf-8'

     $.ajax( {
     type: "POST",
     url: /Person/EditPerson',
     contentType: 'application/json; charset=utf-8',
     data: jform
     }

If this does not solve the issue please post the header information. I am guessing that using the $post is sending "application/x-www-form-urlencoded" data which .NET MVC does not like.

http://api.jquery.com/jQuery.ajax/

Upvotes: 1

Related Questions