2015-07-10 53 views
5

我正在研究MVC應用程序,其中Model類ItemList<Colour>的名稱爲AvailableColours作爲屬性。作爲屬性的對象列表的MVC模型

AvailableColoursColour類的用戶定義子集。我想在複選框列表中顯示所有Colour實例,並且在提交時,AvailableColoursList<Colour>,其中包含已選中的Colour類。

在MVC中做到這一點的最佳方式是什麼?

編輯:我的代碼到目前爲止,雖然我覺得這不是最MVC的方式來做到這一點!

型號

public class Item 
{ 
    public int ID { get; set; } 
    public List<Colour> AvailableColours { get; set; } 
} 

查看

@model MyNamespace.Models.Item 
@using MyNamespace.Models; 
@{ 
    ViewBag.Title = "Create"; 

    var allColours = new List<Colour>(); //retrieved from database, but omitted for simplicity 
} 

<h2>Create New Item</h2> 

@using (Html.BeginForm("Create", "Item", FormMethod.Post)) 
{ 
    <div> 
     @Html.LabelFor(model => model.AvailableColours) 

     @foreach (var colour in allColours) 
     { 

      <input type="checkbox" name="colours" value="@colour.Description" /> 
     } 
    </div> 

    <input type="submit" value="Submit" /> 
} 

控制器

[HttpPost] 
public ActionResult Create(Item item, string[] colours) 
{ 
    try 
    { 
     foreach (var colour in colours) 
     { 
      item.AvailableColours.Add(GetColour(colour));//retrieves from database 

      return RedirectToAction("Index"); 
     } 
    } 
    catch 
    { 
     return View(); 
    } 
} 

回答

18

個模型

public class Item 
{ 
    public List<Colour> AvailableColours { get;set; } 
} 

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

} 

注意Checked財產

查看for循環

@using (Html.BeginForm("Create", "Item", FormMethod.Post)) 
{ 
    <div> 
    @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<br/> 
    } 
    </div> 
<input type="submit" value="Submit" /> 
} 

注意for循環insted的的foreach,使模型綁定和隱藏字段允許值被回發給控制器

Model Binding To A List

控制器發佈

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

    return View(model); 
} 
+0

什麼是'Model.Items'的價值?請參閱我的編輯 - 我從數據庫中提取顏色的完整列表,並允許用戶選擇一個存儲在'AvailableColours'屬性中的子集。 – PTuckley

+0

@ptuckley對不起,這是一個小錯字。該物業是'AvailableColours'。我也對它進行了調整,以適應最初未包含在問題中的更多細節。 – hutchonoid

+0

恐怕這對我來說還沒有多大意義 - 答案中的模型是什麼類型?在'for'循環聲明中有對'Model.AvailableColours'的引用,但是在隱藏字段中引用'Model [i] .ID'? – PTuckley