【问题标题】:how to bind checkbox dynamically in list type model mvc 5如何在列表类型模型mvc 5中动态绑定复选框
【发布时间】:2017-03-28 12:00:14
【问题描述】:

我有课

public class CustomBenefitCommittee
    {
        public int PlanOptionId { get; set; }
        public bool IsChecked { get; set; }
        public string PlanOptionName { get; set; }
    }

我在我的 razer 视图中将这个类作为模型的列表类型

@model List<MIHR.Business.CustomClasses.CustomBenefitCommittee>
@{
    int Counter = 0;
}

<table class="table table-bordered" id="tblPlanLst">
        <thead>
            <tr>
                <th>
                     select
                </th>
                <th>
                    Benefit Option
                </th>

            </tr>
        </thead>

        <tbody>

            @foreach (var Enrol in Model)
            {
                <tr>
                    <td> <input type="checkbox" name="customBenefitCommittee[@Counter].IsChecked"  class="clsCheck" /></td>
                    <td>
                        @Enrol.PlanOptionName
                    </td>

                </tr>
                        Counter++;
            }

        </tbody>
    </table>
<input type="submit" id="btnSubmitSave" value="Save" name="buttonType" class="btn btn  btn-primary">

现在,当我通过选中复选框将此表单发布到控制器时,我在此复选框 IsChecked 属性中始终为假。 谁能帮帮我。

【问题讨论】:

  • 我再次更新了我的答案,请检查它是否适合你
  • 您的复选框没有value。使用@for(int i = 0; i &lt; Model.Count; i++) { @Html.CheckBoxFor(m =&gt; m[i].IsChecked) } 正确生成您的html - 另请参阅Post an HTML Table to ADO.NET DataTable

标签: .net asp.net-mvc c#-4.0


【解决方案1】:

你也可以这样使用:

@{
    var IsChecked = "";
    if (Enrol.IsChecked == true)
    {
        IsChecked = "checked='checked'";
    }
}
<input type="checkbox" name="customBenefitCommittee[@Counter].IsChecked" @IsChecked value="true" />

如果选中复选框,则在此您将获得 true,而未选中复选框时将获得 null

public class CustomBenefitCommittee
    {
        public int PlanOptionId { get; set; }
        public bool? IsChecked { get; set; }
        public string PlanOptionName { get; set; }
    }

或者你也可以这样使用:

@Html.CheckBox("customBenefitCommittee[" + Counter + "].IsChecked", Enrol.IsChecked ?? false, new { @class = "clsCheck" })

或者你也可以这样使用:

@Html.CheckBoxFor(model => model[@Counter].IsChecked)

【讨论】:

    【解决方案2】:

    RAJNIK PATEL 的回答解决了我的问题。

    我有一个视图模型,其中包含选项卡式页面上的其他视图模型。每个选项卡都是不同的视图模型。提交后,所有选项卡都将保存。

    要获得一组动态生成的复选框,我必须让名称表明我正在使用的视图模型中的正确视图模型。

    public class AViewModel{
        public AnotherViewModel {get;set;}
    }
    

    所以我的类型循环生成的复选框看起来像这样。 checkboxid 是我生成的名称。

     @Html.CheckBox("ModifyRolePermViewModel." + checkboxid)
    

    【讨论】:

      猜你喜欢
      • 2011-03-15
      • 2013-03-06
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 2018-07-24
      • 1970-01-01
      相关资源
      最近更新 更多