gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:14:41 25 4
gpt4 key购买 nike

我是 knockout 的新手,并且很难将我的数据从 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 Controller 是
[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”方法来设置与传入数据匹配的每个属性。

关于asp.net-mvc-3 - 将模型数据从 Knockout 发送回 MVC 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8791358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com