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

时间:2015-04-21 17:24:02

标签: jquery asp.net-mvc checkbox toggle

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

然后复制以下代码以替换view home 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>

1 个答案:

答案 0 :(得分:-2)

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

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

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

将pzor代码与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>