ASP.NET MVC 复选框 JQuery 切换只工作一次

ASP.NET MVC checkbox JQuery toggle only work once

我使用VS2013创建了一个ASP.NET MVC项目,并创建了一个模型peron如下图:

然后复制下面的代码来替换视图主页index.cshmtl文件。当我 运行 它时,当我选中复选框时,切换工作一次,隐藏工作,但是当我取消选中时,它不会显示。有人帮忙吗?我四处查看,看到了类似的问题,但没有真正的答案。

Person.cs如下图:

using System;
using System.Linq;
namespace checkbox.Models
{
    public class Person
    {
        public bool IsActive { get; set; }
        public string Email { get; set; }
    }
  }

下面是索引页的代码index.cshtml:

@model checkbox.Models.Person
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Person</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div id="myCheckbox" class="form-group">
            @Html.LabelFor(model => model.IsActive, htmlAttributes: 
            new {     @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.IsActive)
                    @Html.ValidationMessageFor(model => model.IsActive, "", 
                    new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div id="ShowHideMe" class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: 
              new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, 
                  new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "",
                  new { @class = "text-danger" })
            </div>
        </div>

         <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<script type="text/javascript">
  $(function() {
      $('#myCheckbox').change(function() {
          $('#ShowHideMe').toggle($(this).is(':checked'));
      });
  });
</script>

将剃刀视图中的 javascript 更改为此

<script type="text/javascript">
  $(function() {
      $('#@Html.IdFor(model => model.IsActive)').click(function() {
          $('#ShowHideMe').toggle($(this).is(':checked'));
      });
  });
</script>

不要在 div 标签上观看 Change 事件,只需直接使用复选框即可。

将razor代码与javascript混在一起不是一个好的做法,尽可能将它们分开,从长远来看,这将有助于代码的维护

<script type="text/javascript">
  $(function() {
      /*Getting the client id from server side*/
      var isActiveId = '@Html.IdFor(model => model.IsActive)';

      $('#' + isActiveId).click(function() {
          $('#ShowHideMe').toggle($(this).is(':checked'));
      });
  });
</script>