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

标签 c# jquery asp.net-mvc checkbox

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

我的 View 中的复选框

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

我眼中的功能

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

这是我的 Controller 方法

    [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);
    }

最佳答案

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

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

第二,这一行,

url: @Url.Action("UpdateCustomer", "Home"),

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

 url: /Home/UpdateCustomer,

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

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

下面的代码应该可以工作

@Html.CheckBoxFor(m =>customer.IsDone, new { onclick = "UpdateCustomer(this)" })

和脚本

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'
    });
}

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

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

这将呈现带有“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);
        }
    });
}

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

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

关于c# - 如何根据 MVC 中的复选框更改更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44786765/

相关文章:

asp.net-mvc - Asp.Net Mvc - onactionexecuted 在 ActionResult.Execute 之前还是之后被调用?

c# - Winforms 绑定(bind)源问题添加新记录

c# - DDD - 实体状态转换

jquery - 将带有 JQuery 的 CSS 添加到多个类

javascript - jQuery attr 方法可以设置点击处理程序和内部文本

javascript - (typeof variable === "function") 和 jQuery.isFunction() 有什么区别?

c# - 在编辑器模板 (MVC 5) 中访问远程验证属性

c# - IE驱动程序处理后,IEDriverServer.exe进程仍然挂起

c# - 如何在预构建事件中将源文件 (.cs) 添加到资源 (.resx)?

c# - 使用 Linq2Sql 在 C# asp.net MVC 中创建和更新多对多关系