MVC3 RC2 JSON POST绑定无法正常工作 [英] MVC3 RC2 JSON Post Binding not working correctly

查看:66
本文介绍了MVC3 RC2 JSON POST绑定无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过的其他职位就这个问题,并已与拨弄着变化,但仍不能没有得到JSON模型绑定才能正常工作。

我在我的global.asax.cs以下Application_Start方法中:

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

该职位回的数据是这样的:

  {用户名:迈克,密码:密码,坚持:真正}

我的POCO:

 公共类UserLoginViewModel {
    公共字符串用户名{获得;组; }
    公共字符串密码{搞定;组; }
    公共BOOL坚持{搞定;组; }
}

控制器方法正确触发,但有默认UserLoginViewModel对象,用户名= NULL,密码= null,而坚持= FALSE;签名是这样的:

  [HttpPost]
公众的ActionResult登录(UserLoginViewModel模型){
    如果(ModelState.IsValid){
    ...


解决方案

问题是在客户端!我没有将contentType集。

  $。阿贾克斯({
    网址:location.href,
    键入:POST,
    数据:ko.toJSON(本),
    数据类型:JSON
    **的contentType:应用/ JSON的charset = UTF-8,**
    成功:功能(数据){警报(成功); },
    错误:功能(数据){警报(错误); }
});

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

解决方案

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

这篇关于MVC3 RC2 JSON POST绑定无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆