MVC3 RC2 JSON Post Binding not working correctly

点点圈 提交于 2019-12-10 09:34:57

问题


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) { 
    ...

回答1:


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"); }
});


来源:https://stackoverflow.com/questions/4627985/mvc3-rc2-json-post-binding-not-working-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!