Asp.Net MVC 4中的CheckBox

时间:2021-03-15 03:15:01

I have checkbox. When I select the checkbox I want it to automatically change its value in the Database to true and refresh the view and invoke a JQuery method.

我有复选框。当我选中该复选框时,我希望它自动将其在Database中的值更改为true并刷新视图并调用JQuery方法。

I also have a checkbox and label. I want the checkbox to disappear when selected and the text in the label to change.

我还有一个复选框和标签。我希望复选框在选中时消失,并且标签中的文本要更改。

    <h2>Tasks</h2>
<fieldset>
<legend>Tasks</legend>
    <table class="table">
        @foreach(var item in ViewBag.x)
        {
            <tr class="clr">
                <td style="width:520px">
                    @item.User.UserName
                </td>
                <td>
                    @item.date.ToString("MM/dd/yyyy")
                </td>
                </tr>
            <tr class="clr">
                <td>
                    @item.Discription
                </td>
                <td></td>
                </tr>

                <tr>
                    <td ></td>
                <td>
                    <div><input type="checkbox" id="ch" class="ch" /><span id="d"  >Done</span></div>
               </td>

            </tr>
        }

How would I do this in JQuery or ASP MVC?

我将如何在JQuery或ASP MVC中执行此操作?

Image example

图片示例

1 个解决方案

#1


1  

You can listen to the change event on the check box and then make an ajax call to your server to make updates to your db and have your action method return a response. You can check this response and hide/show whatever you want.

您可以在复选框上侦听更改事件,然后对服务器进行ajax调用以对数据库进行更新,并让您的操作方法返回响应。您可以检查此响应并隐藏/显示您想要的任何内容。

You probably want to associate the user id with the checkbox because you need to make this update against a specific user.. You may keep the user id in html 5 data attributes in the check box. Also looks like you are hard coding the id value of checkbox and the span in the loop, which will produce the same value for multiple checkboxes. Id values should be unique. So let's remove the id property value from your markup since we are not using it now.

您可能希望将用户ID与复选框关联,因为您需要针对特定​​用户进行此更新。您可以在复选框中将用户ID保留在html 5数据属性中。也看起来你正在硬编码复选框的id值和循环中的span,这将为多个复选框产生相同的值。 Id值应该是唯一的。因此,我们从标记中删除id属性值,因为我们现在没有使用它。

<div>
   <input type="checkbox" data-user="@item.UserId" class="ch" />
   <span class="msg">Done</span>
</div>

And your javascript code will be

你的javascript代码将是

$(function(){

   $("input.ch").change(function(e){

      var _this=$(this);

      var userId=_this.data("user");
      var isChecked=_this.prop("checked");
      $.post("@Url.Action("Change","Home")", { isChecked :isChecked, userId:userId },
                                                                          function(re){
          if(re.status==="success")
          {
            _this.closest("div").find("span.msg").html(re.message); //update span content
            _this.remove();  // remove checkbox
          }
          else
          {
            alert("Failed to update!");               
          }
      });
   });    

});

I am using Url.Action helper method to generate the relative url to the action method. This code will work if you include your script inside the razor view, but if your javascript code is in an external js file, you should build the path to the app root and pass that to your external js files via some variables as explained in this answer.

我正在使用Url.Action helper方法生成action方法的相对url。如果在剃刀视图中包含脚本,此代码将起作用,但如果您的javascript代码位于外部js文件中,则应构建应用程序根目录的路径,并通过一些变量将其传递给外部js文件,如本文所述回答。

Assuming you have a Change action method in your HomeController which accepts the isChecked value

假设您的HomeController中有一个Change动作方法,它接受isChecked值

[HttpPost]
public ActionResult Change(int userId, bool isChecked)
{

  try
  {
    // to do: using userId  and isChecked param value, update your db
     return Json( new { status="success", message="done"});
  }
  catch(Exception ex)
  {
     //to do : Log ex
     return Json( new { status="error", message="Error updating!"});
  }
} 

#1


1  

You can listen to the change event on the check box and then make an ajax call to your server to make updates to your db and have your action method return a response. You can check this response and hide/show whatever you want.

您可以在复选框上侦听更改事件,然后对服务器进行ajax调用以对数据库进行更新,并让您的操作方法返回响应。您可以检查此响应并隐藏/显示您想要的任何内容。

You probably want to associate the user id with the checkbox because you need to make this update against a specific user.. You may keep the user id in html 5 data attributes in the check box. Also looks like you are hard coding the id value of checkbox and the span in the loop, which will produce the same value for multiple checkboxes. Id values should be unique. So let's remove the id property value from your markup since we are not using it now.

您可能希望将用户ID与复选框关联,因为您需要针对特定​​用户进行此更新。您可以在复选框中将用户ID保留在html 5数据属性中。也看起来你正在硬编码复选框的id值和循环中的span,这将为多个复选框产生相同的值。 Id值应该是唯一的。因此,我们从标记中删除id属性值,因为我们现在没有使用它。

<div>
   <input type="checkbox" data-user="@item.UserId" class="ch" />
   <span class="msg">Done</span>
</div>

And your javascript code will be

你的javascript代码将是

$(function(){

   $("input.ch").change(function(e){

      var _this=$(this);

      var userId=_this.data("user");
      var isChecked=_this.prop("checked");
      $.post("@Url.Action("Change","Home")", { isChecked :isChecked, userId:userId },
                                                                          function(re){
          if(re.status==="success")
          {
            _this.closest("div").find("span.msg").html(re.message); //update span content
            _this.remove();  // remove checkbox
          }
          else
          {
            alert("Failed to update!");               
          }
      });
   });    

});

I am using Url.Action helper method to generate the relative url to the action method. This code will work if you include your script inside the razor view, but if your javascript code is in an external js file, you should build the path to the app root and pass that to your external js files via some variables as explained in this answer.

我正在使用Url.Action helper方法生成action方法的相对url。如果在剃刀视图中包含脚本,此代码将起作用,但如果您的javascript代码位于外部js文件中,则应构建应用程序根目录的路径,并通过一些变量将其传递给外部js文件,如本文所述回答。

Assuming you have a Change action method in your HomeController which accepts the isChecked value

假设您的HomeController中有一个Change动作方法,它接受isChecked值

[HttpPost]
public ActionResult Change(int userId, bool isChecked)
{

  try
  {
    // to do: using userId  and isChecked param value, update your db
     return Json( new { status="success", message="done"});
  }
  catch(Exception ex)
  {
     //to do : Log ex
     return Json( new { status="error", message="Error updating!"});
  }
}