How to link to a list as a property on a model in MVC 3 Razor?

I have a model that looks something like this:

public class EditUserViewModel
    {
        public EditUserViewModel()
        {

        }
        public EditUserDataModel User { get; set; }
    }

With a support object that looks like this:

public class EditUserDataModel
{
    public EditUserDataModel()
    {
        Roles = new List<UserRoleListDataModel>();
    }
    [DisplayName("First Name")]
    public string FirstName { get; set; }
    [DisplayName("Last Name")]
    public string LastName { get; set; }
    [DisplayName("Full Name")]
    public string FullName { get { return FirstName + " " + LastName; } }
    public List<UserRoleListDataModel> Roles { get; set; }
}

And UserRoleListDataModel looks like this:

public class UserRoleListDataModel
{
    public Guid Id { get; set; }
    public string RoleName { get; set; }
    public bool UserIsInRole { get; set; }
}

Then in my Razor file I use it all like this:

@foreach (var role in Model.User.Roles)
{
<tr>
    <td>@role.RoleName</td>
    <td>@Html.CheckBoxFor(x=>role.UserIsInRole)</td>
</tr>
}

The problem I am facing is when I submit the form and click on the action of my controller, the list of roles is not populated with my new model.

Here's what the send action on the controller looks like:

public ActionResult EditUser(EditUserViewModel model) // model.User.Roles is empty.
{
    // Do some stuff...
    return RedirectToAction("UserList");
}

Anyone have any suggestions?

+5
source share
2 answers

Cris Carew was close and brought me back on the right track.

@for (int i=0;i < Model.User.Roles.Count;i++)
{
    @Html.Hidden("User.Roles.Index", i)
    @Html.HiddenFor(x => x.User.Roles[i].RoleName)
    <tr>
        <td>@Html.DisplayFor(x => Model.User.Roles[i].RoleName)</td>
        <td>@Html.CheckBoxFor(x => Model.User.Roles[i].UserIsInRole)</td>
    </tr>
}
+8
source

try this on your razor:

@for (int i=0;i < Model.User.Roles.Count;i++)
{
@Html.Hidden("User.Roles.Index",i);
<tr>
    <td>@role.RoleName</td>
    <td>@Html.CheckBox("User.Roles[" + i + "].UserIsInRole",role.UserIsInRole)</td>
</tr>
}

It is somewhat manual, but must do the job.

+6
source

All Articles