微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc-3 – 将模型数据从Knockout发送回MVC 3

我是淘汰赛的新手,我很难将我的数据从Knockout恢复到我的服务器.我不断收到“没有为此对象定义的无参数构造函数”的错误.任何帮助,将不胜感激.

我的Knockout模型如下

function partSummary(item) {
            var self = this;
            self.ID = ko.observable(item.ID);
            self.serialNumber = ko.observable(item.SerialNumber);
            self.description = ko.observable(item.Description);
            self.manufacturer = ko.observable(item.Manufacturer);
            self.creationDate = ko.observable(item.DateCreated);
            self.active = ko.observable(item.IsActive);
        }

我将数据发送回服务器的代码

self.savePart = function() {
                $.ajax("/PartKO/UpdatePart",{
                    data: ko.toJSON(self.partDetails),type: "post",contentType: 'application/json',dataType: 'json'
                });
            };

我的MVC控制器是

[HttpPost]
    public JsonResult UpdatePart(PartDetail part)
    {
        var dbPart = new PartGenericAccessor();
        dbPart.ID = part.ID;
        dbPart.Load();
        dbPart.Description = part.Description;
        dbPart.IsActive = Convert.ToBoolean(part.IsActive);

        var manufacturers = ManufacturerAccessor.LoadAll<ManufacturerAccessor>();
        if (part.Manufacturer != null)
        {
            var manufacturer = (from p in manufacturers where p.Name == part.Manufacturer select p.ID).First();
            dbPart.ManufacturerID = manufacturer;
        }

        dbPart.Save();

        return Json("Success!!");
    }

而我的服务器端模型是

public class PartDetail
{
    public PartDetail(Guid id,string serial,string description,string manufacturer,DateTime created,bool isActive)
    {
        ID = id;
        SerialNumber = serial;
        Description = description;
        Manufacturer = manufacturer;
        DateCreated = created.ToShortDateString();
        IsActive = isActive.ToString(CultureInfo.InvariantCulture);

    }

    public Guid ID { get; set; }

    public string SerialNumber { get; set; }

    public string Description { get; set; }

    public string Manufacturer { get; set; }

    public string DateCreated { get; set; }

    public string IsActive { get; set; }
}

解决方法

您需要为MVC模型提供无参数构造函数

public class PartDetail
{
    public PartDetail()
    { ...  }
}

当数据从服务器返回时,MVC将使用无参数构造函数创建一个空对象,然后调用’set’方法来设置与进入的数据匹配的每个属性.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐