1

We have a vert complex model with about 3 or 4 nested collections deep. A lot of the data we are pulling from partial calls which 0 bases the ID's when using Editor Templates, so the names and IDs are repeated in our view. I imagine we could change this using jQuery but we are using for each loops at them moment building our own IDs and names. Obviously this is going to break the model binder.

I've done some research and it seems that I can use a for loop and 0-base my IDs and form field names (How to show validation message in mvc4 razor). But having a client and server remember the last number used is probably unreliable. So my question is, do the names and IDs have to be 0 based or can they simply be unique? I would rather use the unique ID of the item instead of the iteration's index. For example, could I modify the following and add my own ID and Name in the Html element object? At the very list, can I mimic the output that would be generated using editorFor and maintain the validation and binding?

@for (var i = 0; i < Model.UsersOfList.Count; i++)
{
   <li>
   @Html.TextBoxFor(m.UsersOfList[i].LoginName, new {@class="textbox_LoginInfoAndPermission"})
   @Html.ValidationMessageFor(m => m.UsersOfList[i].LoginName)

   @Html.TextBoxFor(m.UsersOfList[i].UserName, new {@class="textbox_LoginInfoAndPermission"})
   @Html.ValidationMessageFor(m => m.UsersOfList[i].UserName)
   </li>
}
Community
  • 1
  • 1
Julian Dormon
  • 1,767
  • 4
  • 32
  • 58

1 Answers1

0

I believe you are referring to non-sequential index binding, which allow an arbitrary ID to be used in place of a zero-based, sequential integer.

Example (from linked article):

<form method="post" action="/Home/Create">

    <input type="hidden" name="products.Index" value="cold" />
    <input type="text" name="products[cold].Name" value="Beer" />
    <input type="text" name="products[cold].Price" value="7.32" />

    <input type="hidden" name="products.Index" value="123" />
    <input type="text" name="products[123].Name" value="Chips" />
    <input type="text" name="products[123].Price" value="2.23" />

    <input type="hidden" name="products.Index" value="caliente" />
    <input type="text" name="products[caliente].Name" value="Salsa" />
    <input type="text" name="products[caliente].Price" value="1.23" />

    <input type="submit" />
</form>

This allows you to add/remove items at will without maintaining an index. It also allows you to use non-integer values in the request. It does require an extra hidden field for each item; this allows the model binder to "see" it and the model will be correctly instantiated from the data posted to the controller.

Tim M.
  • 53,671
  • 14
  • 120
  • 163