4

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) { 
    ...
tereško
  • 58,060
  • 25
  • 98
  • 150
Mike
  • 1,405
  • 1
  • 17
  • 27

1 Answers1

14

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"); }
});
Mike
  • 1,405
  • 1
  • 17
  • 27