簡體   English   中英

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>

將您在razor視圖中的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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM