Aegis
Aegis

Reputation: 190

MVC Http Post Action With Variable Parameters

I am having a bit of an issue with an MVC action that I am currently implementing. Simply put, I have a table of users with roles assigned to them. The number of roles per user can range from 1-3 and I am not sure how to reflect this in a POST action of MVC when editing them. To get the roles into the view I use a list of class AccountMapping that contains the role name and ID:

public ActionResult EditUser(User user, EditUserModel model)
    {
        // Omitted model assignments

        model.AccountMappings = _reportUsersRepository.GetAccountMapping(user.UserId).ToList();

        return View(model);            
    }

In the View (using Razor):

 @foreach (var item in @Model.AccountMappings)
 {
      <div>
          <p>@item.Target_Type.Replace('_', ' ')</p>

          <input name="@item.Role_Name" value="@item.Target_Id" type="number" placeholder="Role Id" required />
      </div>                             
 }

How would I go about structuring the POST action to take into account these inputs? I am using the same model for the POST action and I am aware that the AccountMapping list would contain no results on postback. I am not sure about using the FormsCollection method because you need to know the name of the keys in order to retrieve the values. Am I missing something obvious?

Many Thanks.

Upvotes: 2

Views: 658

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93611

Expanding on my comment, If you use indexing instead of foreach, then it can correctly name and map the individual items in a collection back to the posted input collection. e.g.:

 @for (int i = 0; i < Model.AccountMappings.Count(); i++)
 {
      <div>
          @Html.EditorFor(x=>Model.AccountMappings[i])
      </div>                             
 }

If you look at the generated HTML you will see the inputs are named uniquely based on their index position.

These will be automatically mapped back into a receiving collection (assuming your postback takes the same object type as your view model that was passed to the view).

Upvotes: 2

Related Questions