Populate List<Objects> From Mvc 3 view

99封情书 提交于 2019-12-10 21:26:54

问题


I Have a Viewmodel based on Nominees . And i can have Multiple Nominees for the viewmodel.

I want to populate the Ilist From the view . Here are my 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; }        
}

I want to populate all Nominess automatically when i press submit . so how should i create by view and make it automatically populate List automatically ? instead of serparate objects ?


回答1:


You could use editor templates:

@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>
}

and then you define a custom editor template for the Nominee model (~/Views/Shared/EditorTemplates/Nominee.cshtml) which will automatically be rendered for each element of the Nominees collection:

@model Nominee

<div>
    @Html.EditorFor(x => x.FirstName)
    @Html.EditorFor(x => x.LastName)
    ...
</div>



回答2:


say for example the Nominee looks like

public class Nominee{
 public int Id{get;set;}
 public string Name{get;set;}
 public int Age {get;set;}
}

the view would look like

@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>
}

read more about model binding to a list



来源:https://stackoverflow.com/questions/9800211/populate-listobjects-from-mvc-3-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!