Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind to a List as a Property on a Model in MVC 3 Razor?

I've got a model that looks something like this:

public class EditUserViewModel
    {
        public EditUserViewModel()
        {

        }
        public EditUserDataModel User { get; set; }
    }

With a backing 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 am using the whole thing like so:

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

The problem I'm having, is when I submit the form and hit my controller action, the Roles list is not populated on my new model.

Here is what the submit 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?

like image 684
Joe Avatar asked Mar 16 '12 16:03

Joe


People also ask

What is bind property razor pages?

Model Binding in Razor Pages is the process that takes values from HTTP requests and maps them to handler method parameters or PageModel properties.

What is bind property in MVC?

The [Bind] attribute will let you specify the exact properties of a model should include or exclude in binding. In the following example, the Edit() action method will only bind StudentId and StudentName properties of the Student model class. You can also exclude the properties, as shown below.


2 Answers

Cris Carew was close, and got me 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>
}
like image 95
Joe Avatar answered Nov 15 '22 11:11

Joe


try this in 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's somewhat manual, but should do the job.

like image 43
Chris Carew Avatar answered Nov 15 '22 10:11

Chris Carew