【问题标题】:serialize to C# MVC model class from knockout Model从淘汰模型序列化为 C# MVC 模型类
【发布时间】:2013-07-15 15:20:00
【问题描述】:

-----敲掉js代码------------

var User = function () {
    this.UserName = ko.observable();
    this.Password = ko.observable();
};


var LoginViewModel = function () {
    var self = this;
    this.LoginName = '';
    this.Password = '';
    this.errorvisible = ko.observable(false);

    this.User = ko.observable(new User());
    this.returnurl = '<%: Url.Action("Home","Home") %>';
    this.Login = function () {
        $.ajax({
            url: '../api/LoginApi/',
            contentType: "Application/Json , UTF-8",
            dataType: 'json',
            type: 'POST',
            data: ko.toJson(self.User()),
            success: function (data) {
                var result = data.ID;
                if (result == 400) {
                    self.errorvisible(true);
                } else {
                    self.errorvisible(false);
                    window.location.href = self.returnurl;
                }
            },
            error: function () {
                alert('failed');
            }
        });
    };

};
ko.applyBindings(new LoginViewModel());

------用户模型类-------

 public class User
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string UserName { get; set; }
    }


  public void Post(User value)
  {
      //This is the post method  the webAPI which should get the values of properties in User class
  } 

当调试器命中 Post Method User 类实例为 Null(即 Value 为 Null) 而不是像 UserName 和 Password 这样的属性中的值

【问题讨论】:

  • 您的内容类型看起来很奇怪。你可以试试contentType: 'application/json'吗?
  • ModelState 中有没有消息?如果没有下载这个并观察输出nuget.org/packages/microsoft.aspnet.webapi.tracing
  • 亲爱的@chitta 你到底在做什么我的意思是你正在从 UI 发送数据,如果你是那么请也发布你的 HTML 代码
  • 请检查 firebug 和 fiddler 以查看正在传递给服务器的内容类型和数据
  • @nemesv,我是 Json 的新手,并且可以淘汰,谢谢它现在可以使用

标签: json asp.net-mvc-4 serialization knockout.js asp.net-web-api


【解决方案1】:

您的内容类型contentType: "Application/Json , UTF-8", 错误。

应该是:

contentType: 'application/json; charset=utf-8'

或者简单地说:

contentType: 'application/json'

如果没有正确的内容类型,Wep.API 无法正确处理您的请求,因此您将获得 null 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2013-01-09
    • 1970-01-01
    • 2018-01-23
    • 2013-12-24
    • 2013-08-12
    • 2014-04-08
    相关资源
    最近更新 更多