Select items from the <T> list in MVC 4 using model binding

Considering class

public class Person
{
    // Some general properties

    public List<Hobby> Hobbies { get; set; }
}

public class Hobby
{
    // Some properties e.g. Name, etc.
}

static List<Hobby> AllHobbies { get; }

Is it possible to create a view that allows the user to choose his hobby using model binding?

In the view, one could go through AllHobbiesand display <input type="checkbox" />for each, and then connect the selected values ​​manually in the feedback controller. It seems that this should be feasible with reference to the model, but I do not see how.

+5
source share
1 answer

Of course, I would recommend that you use editor templates.

Suppose a hobby has a name and a logical field indicating whether it was selected by the user:

public class Hobby
{
    public string Name { get; set; }
    public bool Selected { get; set; }
}

:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var person = new Person
        {
            Hobbies = new[]
            {
                new Hobby { Name = "hobby 1" },
                new Hobby { Name = "hobby 2", Selected = true },
                new Hobby { Name = "hobby 3" },
            }.ToList()
        };
        return View(person);
    }

    [HttpPost]
    public ActionResult Index(Person person)
    {
        var selectedHobbies = person
            .Hobbies
            .Where(x => x.Selected).Select(x => x.Name);
        string message = string.Join(",", selectedHobbies);
        return Content("Thank you for selecting: " + message);
    }
}

, , :

@model Person

@using (Html.BeginForm()) 
{
    <h2>Hobbies</h2>
    @Html.EditorFor(x => x.Hobbies)
    <button type="submit">OK</button>
}

, Hobbies (~/Views/Home/EditorTemplates/Hobby.cshtml → , ):

@model Hobby

<div>
    @Html.LabelFor(x => x.Selected, Model.Name)
    @Html.HiddenFor(x => x.Name)
    @Html.CheckBoxFor(x => x.Selected)
</div>

+11

All Articles