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.
for (int i = 0; i < Model.AccountMappings.Count(); i++)instead offoreach, using@Html.EditorFor(x=>Model.AccountMappings[i])etc will work correctly.