如何根据 MVC 中的复选框更改更新数据库

zlo*_*pez 2 c# checkbox asp.net-mvc jquery

当选中或取消选中复选框时,我试图更新我的数据库。我希望它在单击复选框时更新。这是我到目前为止所拥有的,但我的控制器从未被击中。我能做什么来修复它?理想情况下,我想将 customer.IsDone 和 customer.Id 的新值传递给我的控制器,但我不知道如何执行此操作。

在我看来复选框

    <td>@Html.CheckBoxFor(m => customer.IsDone, new { onclick = "UpdateCustomer(IsDone)" })</td>
Run Code Online (Sandbox Code Playgroud)

我认为的功能

function UpdateCustomer(isDone) {
        $.ajax({
            type: 'POST',
            url: @Url.Action("UpdateCustomer", "Home"),
            data: { check: isDone },
            success: success,
            dataType: 'json'
        });
    }
Run Code Online (Sandbox Code Playgroud)

这是我的控制器方法

    [HttpPost]
    public ActionResult UpdateCustomer(bool check)
    {
        //code will be here to update the db

        var customers = new CustomerGetAll();
        var list = customers.Execute();

        return View("Customers", list);
    }
Run Code Online (Sandbox Code Playgroud)

Shy*_*yju 5

我在您的代码中发现了一些问题。

首先,您IsDone在调用方法时传递变量UpdateCustomer。但在哪里isDone定义的呢?

其次,这一行,

url: @Url.Action("UpdateCustomer", "Home"),
Run Code Online (Sandbox Code Playgroud)

助手Url.Action将输出一个字符串,您的代码在浏览器中呈现时将如下所示

 url: /Home/UpdateCustomer,
Run Code Online (Sandbox Code Playgroud)

现在浏览器的javascript框架通常认为后面的第二部分:是一个js变量,如果你没有定义它,它会抛出一个关于使用未定义变量的语法错误!但既然我们有了 \,您将收到另一个“无效的正则表达式标志”语法错误!

您应该将结果用引号括起来以避免出现此问题。

下面的代码应该可以工作

@Html.CheckBoxFor(m =>customer.IsDone, new { onclick = "UpdateCustomer(this)" })
Run Code Online (Sandbox Code Playgroud)

和脚本

function UpdateCustomer(elem) {
    var isDone = $(elem).is(':checked');
    $.ajax({
        type: 'POST',
        url: "@Url.Action("UpdateCustomer", "Home")",
        data: { check: isDone },
        success: function(res) {
            console.log(res);
        },
        dataType: 'json'
    });
}
Run Code Online (Sandbox Code Playgroud)

另外,如果您想更新特定的客户记录,您可能还想在进行 ajax 调用时传递客户 ID。您可以将其保留在复选框标记上的 html 5 数据属性中,并根据需要阅读并使用它。

@Html.CheckBoxFor(m =>customer.IsDone, new { onclick = "UpdateCustomer(this)",
                                                       data_customerid = customer.Id })
Run Code Online (Sandbox Code Playgroud)

这将呈现带有“data-customerid”的 html5 数据属性的复选框。您现在要做的就是读取这个值并通过 ajax 发送它

function UpdateCustomer(elem) {
    var isDone = $(elem).is(':checked');
    var cid = $(elem).data('customerid');
    $.ajax({
        type: 'POST',
        url: '@Url.Action("UpdateCustomer", "Home")',
        data: { check: isDone,customerId:cid },
        success: function(res) {
            console.log(res);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

确保您的服务器操作方法有一个新参数来接受我们从客户端代码发送的客户 ID

[HttpPost]
public ActionResult UpdateCustomer(bool check,int customerId)
{
   // to do  : Save and return something
}
Run Code Online (Sandbox Code Playgroud)