MVC Model with a list of objects as property

后端 未结 3 1316
猫巷女王i
猫巷女王i 2020-12-14 03:54

I am working on an MVC application where the Model class Item has a List named AvailableColours as a property.

<

3条回答
  •  半阙折子戏
    2020-12-14 04:51

    Models

    public class Item
    {
       public List AvailableColours { get;set; }
    }
    
    public class Colour
    {
        public int ID { get; set; }
        public string Description { get; set; }
        public bool Checked { get; set; }
    
    }
    

    Note the Checked property

    View for loop

    @using (Html.BeginForm("Create", "Item", FormMethod.Post)) 
    {
       
    @Html.LabelFor(model => model.AvailableColours) @for(var i = 0; i < Model.AvailableColours.Count; i++) { @Html.HiddenFor(m => Model.AvailableColours[i].ID) @Html.HiddenFor(m => Model.AvailableColours[i].Description) @Html.CheckBoxFor(m => Model.AvailableColours[i].Checked) @Model.AvailableColours[i].Description
    }
    }

    Note the for loop insted of foreach to enable model binding and the hidden fields to allow the values to be posted back to the controller

    Model Binding To A List

    Controller post

    [HttpPost]
    public ActionResult Create(Item model)
    {
        //All the selected are available in AvailableColours
    
        return View(model);
    }
    

提交回复
热议问题