繁体   English   中英

如何使用ASP.NET MVC和KnockoutJS很好地添加记录?

[英]How to add record well using ASP.NET MVC and KnockoutJS?

<button class="btn btn-primary" data-bind="click:function(){show('add');}">Add</button>

我的目的是使用自动ID号将输入记录值添加到后端。 但是,单击“添加”按钮后,显示“内部服务器错误”。 该记录有时被保存到数据库中。 但Id为0。我已经将Id属性设置为Nullable。 以下是我的Add函数和对象。 我可以从你们这些聪明的人那里得到一些想法吗? 非常感谢你。

    self.addCustomer = function () {
    debugger;
    var cus = { Name : self.cusName(), Address: self.cusAddress()}
    var url = "/Customer/AddCustomer";
    $.ajax({
        type: "POST",
        url: url,
        data: cus,
        success: function (data) {
            alert("Insert Successful!");
            GetCustomers();
            $('#AddCustomer').modal('hide');
        },
        error: function (error) {
            alert(error.statusText);
        }
    });
};
self.customers = ko.observableArray([]);
GetCustomers();
function GetCustomers() {
    $.ajax({
        type: "GET",
        url: "/Customer/GetCustomer",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            self.customers(data);
        },
        error: function (error) {
            alert(error.statusText);
        }
    });
}
self.getSelected = function (cus) {
    self.cusId(cus.Id),
    self.cusName(cus.Name),
    self.cusAddress(cus.Address)
};

后端发布操作。

    [HttpPost]
    public ActionResult AddCustomer(CustomerModel customer)
    {
        var cus = new Customer
        {
            //Id = customer.Id,
            Name = customer.Name,
            Address = customer.Address
        };
        customerContext.Customers.Add(cus);
        customerContext.SaveChanges();
        return null;
    }

反序列化时,如果未在数据中指定一个,则为控制器端点的所有参数指定一个“默认”值。 C#中整数的默认值为0。因此,除非明确告知不要,否则CustomerModel的所有整数属性都将为0。

我假设CustomerModel.ID是一个int,因为您没有包含该代码。 如果正确,请尝试将其设置为nullable<int> 这样,当未指定值时,默认值将为null

同样的问题也适用于Customer实体模型。 如果该ID属性不是可为空的值,则除非EntityFramework知道它是一个自动递增(标识)字段,否则它将被默认为0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM