Matt Burland
Matt Burland

Reputation: 45135

Can't get controller to parse JSON back to model

I have a controller that has an action that is supposed to take a POST'ed json object:

[HttpPost]
public ActionResult EditProject(ProjectDetails project)
{
    return Json(project);
}

However, what actually gets returned is a new, empty project object. It doesn't seem to actually populate the project object with anything other than the ID (which comes from the url mywebsite/mycontroller/EditProject/3 for example).

My ProjectDetails object looks something like this:

public class ProjectDetails
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public List<Factor> factors { get; set; }

    public ProjectDetails() 
    { 
        factors = new List<Factor>();
    }

    public ProjectDetails(Project p)
    {
        ID = p.PrjID; 
        Name = p.Name;
        Date = p.PrjDate;
        factors = p.factors;
    }
}

And JavaScript code to post looks like this:

    function save() {
        var data = {
            ID: 4,
            Name: "foo",
            Date: Date.now(),
            factors: []
        };

        $.ajax(window.location.href, {
            type: "POST",
            dataType: "json",
            data: JSON.stringify({ project: data }),
            success: function () {
                alert("done");
            }
        });
    }

I've been messing around with variations on this for a couple of hours and it stubbornly ignores the post data I sent and instead builds a new ProjectDetails with only the ID defined.

Any ideas?

I've even tried using the JSON data produced by the GET request to the same controller and sending it straight back (so it's gotta be in the right format, right?) and it still ignores it.

Update

Looking at this a bit more, my request is being sent as application/json, but when I set a break point in my controller and check the request, it's application/x-www-form-urlencoded and I can find my json string in Request.Form[0]. But from everything else I was reading, this should just work. I shouldn't have to retrieve the json string and deserialize it myself. So what am I missing here?

Upvotes: 2

Views: 1528

Answers (1)

Matt Burland
Matt Burland

Reputation: 45135

Ok, I've fixed it. Turns out that despite the fact that Firebug showed the request headers as being application/json, you have to actually explicitly set them in your AJAX settings by adding:

contentType: "application/json"

facepalm

Upvotes: 4

Related Questions