Asp.net mvc 4 带ICollection的模型绑定复选框

Asp.net mvc 4 带ICollection的模型绑定复选框,asp.net-mvc-4,model-binding,checkboxfor,Asp.net Mvc 4,Model Binding,Checkboxfor,我的班级是 public partial class Team { public Team() { this.Trials = new HashSet<Trials>(); } public int TeamId { get; set; } public string TeamName { get; set; } public

我的班级是

public partial class Team
    {
        public Team()
        {
            this.Trials = new HashSet<Trials>();               
        }

        public int TeamId { get; set; }
        public string TeamName { get; set; }
        public string TeamDescription { get; set; }
        public virtual ICollection<Trials> Trials { get; set; }
    }
公共部分类团队
{
公共团队()
{
this.Trials=new HashSet();
}
public int TeamId{get;set;}
公共字符串TeamName{get;set;}
公共字符串TeamDescription{get;set;}
公共虚拟ICollection试验{get;set;}
}
而且景色很美

@model Project.Classes.Team

 <td>
         @for (int i = 0; i < Model.Trials.Count; i++ )
         {                
                @Html.DisplayFor(x => Model.Trials.ElementAt(i).Name)
                @Html.HiddenFor(x => Model.Trials.ElementAt(i).Name)
                @Html.HiddenFor(x => Model.Trials.ElementAt(i).TrialID)
                @Html.CheckBoxFor(x => Model.Trials.ElementAt(i).isChk)  
             <br />               
         } 
</td>
@model Project.Classes.Team
@for(int i=0;iModel.Trials.ElementAt(i.Name)
@HiddenFor(x=>Model.Trials.ElementAt(i.Name)
@HiddenFor(x=>Model.Trials.ElementAt(i.TrialID)
@CheckBoxFor(x=>Model.Trials.ElementAt(i.isChk)

}

显示视图时,将显示模型(团队)中的试验对象(3个试验)并显示在表单上,但当表单发布后,在控制器中,我没有得到任何试用值,它显示0个试用…我通过在类中将ICollection更改为IList来完成,但是…Team类是由EF自动生成的,当项目重新运行时,忘记更改,所以我想在您中使用ICollection plz来完成…

View/Shared/EditorTemplates
文件夹,使用以下代码添加名为
Trials.cshtml
的新视图(创建为局部视图)

然后在您的视图中,将循环替换为
@Html.EditorFor(m=>m.Trials)

EditorFor
将使用用于回发的索引器正确命名集合项,例如,它将生成

<input type="hidden" name="Trials[0].ID" ...>
<input type="hidden" name="Trials[1].ID" ...>


注意:您是真的想在一个表格单元格中显示整个集合,还是说每行显示一个
Trial
,并在单独的
td
元素中显示名称和复选框?f因此,您可以在
EditorTemplate

中添加
tr
td
元素,在循环中使用以下格式:
@Html.HiddenFor(x=>x.Trials[i].Name)
它说不能对icolection类型的表达式应用带[]的索引您说您已经将其更改为
IList
,这正是你需要的。或者,您可以为
试用版创建自定义
编辑器模板
,并使用
@Html.EditorFor(x=>x.Trials)
(无循环)谢谢Stephen..对不起,我是MVC新手,从未使用过Editor Temp…你能给我一些关于编辑器模板的好教程吗?请…谢谢我用
编辑器模板添加了一个答案(对不起,我误解了你关于使用
IList
)非常感谢…谢谢…我可以整理分发问题…请给我一个编辑模板的教程…我知道你在这里做了什么,但想知道整个理论…再次感谢你没有遇到好的教程,但可能会让您更好地理解Hi Stephen很抱歉再次打扰您…如果我需要为同一个Trials类添加另一个编辑器模板,我想在其中显示multiple select dropdownlist最佳方法是什么…我想使用multiselect在团队中添加多个试用@Html.ListBoxFor(model=>model.TrialID,new SelectList(ViewBag.trials,“TrialID”,“Name”),new{@class=“selected select”,data_placeholder=“select trials…”,style=“width:500px;”,tabindex=“4”}不能将多个选择绑定到单个值
TrialID
需要是一个数组。您需要创建视图模型来表示要显示和编辑的内容。也许会有帮助。如果没有,你需要问另一个问题谢谢Stephen.我在Teams类中声明了一个int[],并用multiselect绑定了它,得到了所选的测试结果…再次感谢
@model Project.Classes.Team
....
@Html.EditorFor(m => m.Trials)
<input type="hidden" name="Trials[0].ID" ...>
<input type="hidden" name="Trials[1].ID" ...>