Select Items from List<T> in MVC 4 using Model Binding

丶灬走出姿态 提交于 2020-01-11 05:37:08

问题


Given a 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 select his hobbies using model binding?

It would certainly be possible in the view to loop through AllHobbies and render an <input type="checkbox" /> for each, then wire up the selected values by hand in the postback controller. It seems that this should be doable with model binding, but I don't see how.


回答1:


Sure, I would recommend you using editor templates.

Let's suppose that a hobby has a name and a boolean field indicating whether it was selected by the user:

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

then a controller to feed the model into the view and process the form submission:

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);
    }
}

then a view containing the form allowing the user to select hobbies:

@model Person

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

and a corresponding editor template which will automatically be rendered for each element of the Hobbies collection (~/Views/Home/EditorTemplates/Hobby.cshtml -> notice that the name and location of the template is important):

@model Hobby

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

For more advanced editing scenarios I would recommend you going through the Steven Sanderson's blog post on this topic.



来源:https://stackoverflow.com/questions/10984727/select-items-from-listt-in-mvc-4-using-model-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!