2

I have this classes:

public class Bar
{
    public string Name;
}

puclic class Foo
{
    public string Age {get;set;}
    public List<Bar> Bars {get;set;}
}

I want to display in Foo View infomations about each of its Bar, for example:

@Html.EditorFor(model => Model.Bars.ElementAt(1).Bar.Name)

Is this the correct approach using Razor/Html Helpers? If i change the value of Bars[1] then post to controlller it will update the value in model? And for last, how i can create dynamically bars using the foo view and assign them to foo's bar list model?

Rieth
  • 305
  • 1
  • 4
  • 13
  • It needs to be `@Html.EditorFor(m => m.Bars[0].Name)` to display the first one, but if you want to display all items in the collection, use a `for` loop or `EditorTemplate` –  Apr 02 '16 at 03:43

1 Answers1

1

To display all Bar items (and be able to submit to a POST method with parameter Foo model, then you need a for loop

for(int i = 0; i < Model.Bars.Count; i++)
{
    @Html.TextBoxFor(m => m.Bars[i].Name)
}

or (better), use an EditorTemplate for typeof Bar

/Views/Shared/EditorTemplates/Bar.cshtml

@Model.Bar
@Html.TextBoxFor(m => m.Name)

and in the main view

@Html.EditorFor(m => m.Bars)

The EditorFor() method will generate the correct html for each item in your collection

To dynamically add and remove Bar items, refer to POST a form array without successful and Submit same Partial View called multiple times data to controller?

Community
  • 1
  • 1