我有一个基于被提名者的Viewmodel。我可以为视图模型提供多个提名。
我想从视图中填充Ilist。这是我的viewmodels
public class DebitViewModel:IValidatableObject
{
public string AgentName { get; set; }
public Debit Debit { get; set; }
public Policy Policy { get; set; }
public PolicyType PolicyType { get; set; }
public Customer Customer { get; set; }
public IList<PolicyType> PolicyTypes { get; set; }
public List<Nominee> Nominees { get; set; }
public Dictionary<int,string> OccupationTypes { get; set; }
}
我想在按提交时自动填充所有Nominess。那么我应该如何通过视图创建并使其自动填充List?而不是serparate对象?
答案 0 :(得分:1)
您可以使用编辑器模板:
@model DebitViewModel
@using (Html.BeginForm())
{
... some input fields for the other properties that we are not interested in
@Html.EditorFor(x => x.Nominees)
<button type="submit">OK</button>
}
然后为Nominee
模型(~/Views/Shared/EditorTemplates/Nominee.cshtml
)定义自定义编辑器模板,该模板将自动为Nominees
集合的每个元素呈现:
@model Nominee
<div>
@Html.EditorFor(x => x.FirstName)
@Html.EditorFor(x => x.LastName)
...
</div>
答案 1 :(得分:0)
例如,Nominee
看起来像
public class Nominee{
public int Id{get;set;}
public string Name{get;set;}
public int Age {get;set;}
}
视图看起来像
@for (int i = 0; i < Model.Nominees.Count(); i++)
{
<tr>
<td>@Html.TextBoxFor(m => m.Nominees[i].Name)</td>
<td>@Html.TextBoxFor(m => m.Nominees[i].Age)</td>
</tr>
}