Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 RC2 JSON Post Binding not working correctly

I've seen other posts on this subject and have fiddled with variations but still cannot not get the JSON model binding to work correctly.

I have the following in my global.asax.cs Application_Start method:

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

The post back data looks like this:

{"UserName":"Mike","Password":"password","Persist":true}

My PoCo:

public class UserLoginViewModel {
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool Persist { get; set; }
}

The controller method fires properly but has default UserLoginViewModel object with UserName = null, Password = null, and Persist = false; the signature looks like this:

[HttpPost]
public ActionResult Logon(UserLoginViewModel model) {
    if (ModelState.IsValid) { 
    ...
like image 478
Mike Avatar asked Dec 09 '22 11:12

Mike


1 Answers

The problem is on the client side! I didn't have the contentType set.

$.ajax({
    url: location.href, 
    type: "POST",
    data: ko.toJSON(this),
    datatype: "json",
    **contentType: "application/json charset=utf-8",**
    success: function (data) { alert("success"); }, 
    error: function (data) { alert("error"); }
});
like image 196
Mike Avatar answered Dec 28 '22 11:12

Mike