Select Items from List in MVC 4 using Model Binding

后端 未结 1 1601
名媛妹妹
名媛妹妹 2021-01-13 09:56

Given a class

public class Person
{
    // Some general properties

    public List Hobbies { get; set; }
}

public class Hobby
{
    // Some pr         


        
相关标签:
1条回答
  • 2021-01-13 10:48

    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.

    0 讨论(0)
提交回复
热议问题