【问题标题】:How to add record well using ASP.NET MVC and KnockoutJS?如何使用 ASP.NET MVC 和 KnockoutJS 很好地添加记录?
【发布时间】:2018-01-22 20:32:55
【问题描述】:
<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# asp.net-mvc knockout.js


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,伙计。我将 Id 属性更改为可为空的 int。但是现在添加和编辑点击事件总是显示“内部服务器错误”对话框。我将 Application_EndRequest 方法放在 Global.aspx.cs 中,但仍然无法正常工作。 :(
    • 否则,它会工作一段时间,名称和地址数据保存到数据库中,但Id仍然是0。内部服务器错误是下一个错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 2010-09-06
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多