在我的编辑屏幕中,我似乎无法在POST时获得模型中的ICollection返回到控制器。为了简单起见,有两个模型,一个Pattern表:
[Table("Pattern")]
public partial class Pattern
{
public Pattern()
{
PatternFeatureAssociations = new HashSet<PatternFeatureAssociation>();
}
[Key]
public int PkID { get; set; }
[Required]
public string PatternNumber { get; set; }
public DateTime? CreatedOn { get; set; }
public int? CrearedBy { get; set; }
public DateTime? UpdatedOn { get; set; }
public int? UpdatedBy { get; set; }
public virtual ICollection<PatternFeatureAssociation> PatternFeatureAssociations { get; set; }
}
和PatternFeatureAssociation表:
[Table("PatternFeatureAssociation")]
public partial class PatternFeatureAssociation
{
[Key]
public int PkID { get; set; }
public int PatternID { get; set; }
public int FeatureName { get; set; }
public int FeatureDesc { get; set; }
public DateTime CreatedOn { get; set; }
public int CreatedBy { get; set; }
public DateTime? UpdatedOn { get; set; }
public int? UpdatedBy { get; set; }
public virtual Pattern Pattern { get; set; }
}
然后我有一个包含以下内容的ViewModel:
public class EditingViewModel
{
public List<Pattern> patterns { get; set; }
other values...
}
我的视图(这是部分版本)然后从ViewModel:离开
@model TEST.ViewModels.EditingViewModel
@using (Html.BeginForm("Edit", "Patterns", FormMethod.Post))
{
<input class="btnSave" type="submit" value="Save Changes" />
<br /><br />
for (int s = 0; s < Model.patterns.Count; s++)
{
@Html.HiddenFor(modelItem => Model.patterns[s].PatternNumber)
@Html.HiddenFor(modelItem => Model.patterns[s].PkID)
<p><b>Pattern Number: </b>@Html.DisplayFor(modelItem => Model.patterns[s].PatternNumber)</p>
@foreach (var item in Model.patterns[s].PatternFeatureAssociations)
{
@Html.HiddenFor(modelItem => item.PkID)
@Html.HiddenFor(modelItem => item.PatternID)
<h3>Feature Name</h3>
<div>@Html.EditorFor(modelItem => item.FeatureName)</div>
<h3>Feature Description</h3>
<div>@Html.EditorFor(modelItem => item.FeatureDesc)</div>
}
}
}
但是,当我单击"保存"并返回到控制器时,ViewModel不会返回PatternFeatureAssociations数据。在获取视图的过程中,数据确实全部通过。
[HttpPost]
public ActionResult Edit(EditingViewModel searchedit)
{
return View();
}
您需要使用for
循环而不是foreach
:进行索引
@for(var i = 0; i < Model.patterns[s].PatternFeatureAssociations; i++)
{
@Html.HiddenFor(modelItem => Model.patterns[s].PatternFeatureAssociations[i].PkID)
@Html.HiddenFor(modelItem => Model.patterns[s].PatternFeatureAssociations[i].PatternID)
<h3>Feature Name</h3>
<div>@Html.EditorFor(modelItem => Model.pattern s[s].PatternFeatureAssociations[i].FeatureName)</div>
<h3>Feature Description</h3>
<div>@Html.EditorFor(modelItem => Model.patterns[s].PatternFeatureAssociations[i].FeatureDesc)</div>
}
这将确保使用模型绑定器所期望的预期命名约定生成相关输入。
模型绑定到列表