Search code examples
c#.netasp.net-mvcrazorform-helpers

Razor form helpers with a collection, how to name form elements correctly?


I have a page where a Manager registers, and during the restoration they can add up o 3 Users.

The User form is in a partial.

The view model has a collection of Users:

public class ManagerRegistrationViewModel
{
  public List<User> Users {get; set;}

  public ManagerRegistrationViewModel()
  {
      Users = new List<User>();
      Users.Add(new User(....));
      Users.Add(new User(....));
      Users.Add(new User(....));
  }
}

public ActionResult  ManagerRegistration()
{
   var vm = new ManagerRegistrationViewModel();

   return View("ManagerRegistration", vm);
}

ManagerRegistration.cshtml:

@using (Html.BeginForm())
{

<div id="users">
    @{  Html.RenderPartial("_User", Model.Users[0]); }
    @{  Html.RenderPartial("_User", Model.Users[1]); }
    @{  Html.RenderPartial("_User", Model.Users[2]); }
</div>


}

My question is, in the partial, I am NOT currently using the Html helpers.

For example, and text input looks like:

<input type=text name="Users[0].Name" />

But I want to use the Html helpers for textboxes and dropdown lists etc. because for Edit pages it sets the current value/state of the form element.

How can I use Html helpers in this scenerio?

The form elements have to be named like:

Users[x].Property

I would ideally like to somehow keep using the strongly typed way like:

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

Solution

  • For these scenarios, you should be using EditorTemplates not partial views, otherwise you won't get any proper naming on your fields.

    So you'd have:

    @Html.EditorFor(m => m.Users[0])
    @Html.EditorFor(m => m.Users[1])
    @Html.EditorFor(m => m.Users[2])
    

    Or more appropriately, in a for loop:

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