Fill List <Objects> From Mvc 3 Viewer

I have a Viewmodel based on nominees. And I may have multiple viewmodel nominees.

I want to populate an Ilist from a view. Here are my view models

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 fill in all the Nominess automatically when I hit submit. so how am I supposed to create by view and auto-fill the list? instead of gray objects?

+3


source share


2 answers


You can 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 template for model Nominee

( ~/Views/Shared/EditorTemplates/Nominee.cshtml

) that will automatically render for every item in the collection Nominees

:

@model Nominee

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

      

+1


source


let's say for example Nominee

looks like

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

      

the view will 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>
}

      

More on binding a model to a list

0


source







All Articles