Anders
Anders

Reputation: 1042

Refer to property within collection in MVC view, using Razor

I have a model that looks somewhat like this:

public class MyClass {
   public string Id { get; set; }
   public List<SubItem> SubItems { get; set; }
}

public class SubItem {
   public string Key { get; set; }
   public string Value { get; set; }
}

In my view, I want to submit form data to MyClass, so I can create an object of MyClass. It looks like this:

@model Models.MyClass

@using (Html.BeginForm()){

<div>
   @Html.DisplayFor(model => model.Id): @Html.EditorFor(model => model.Id)
</div>
<div>
   @Html.DisplayFor(model => ???): @Html.EditorFor( ??? )
</div>

<input type="submit" value="create"/>
}

You see the question marks (???) where I am in doubt. How do I get to add to this collection? I know it is a sub form of sorts, but how do I do it without much complication. If I needed to show the items, I would do a foreach(var item in Model.SubItems) { ... }. But this is different. How do I handle this?

Upvotes: 0

Views: 382

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239380

It's really not different than displaying each item individually:

@for (int i=0; i<Model.SubItems.Length; i++)
{
    <div>
        @Html.DisplayFor(m => m.SubItems[i].Key): @Html.EditorFor(m => m.SubItems[i].Key)
    </div>
    <div>
        @Html.DisplayFor(m => m.SubItems[i].Value): @Html.EditorFor(m => m.SubItems[i].Value)
    </div>
}

UPDATE

Changed code above to make sure names and index values are correctly generated. Also, this will now work with scenario of no initial items, as well. Just change the i<Model.SubItems.Length condition to i<3, or whatever number of iterations you'd like.

Upvotes: 2

Related Questions