5
我正在研究MVC应用程序,其中Model类Item
的List<Colour>
的名称为AvailableColours
作为属性。作为属性的对象列表的MVC模型
AvailableColours
是Colour
类的用户定义子集。我想在复选框列表中显示所有Colour
实例,并且在提交时,AvailableColours
是List<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();
}
}
什么是'Model.Items'的价值?请参阅我的编辑 - 我从数据库中提取颜色的完整列表,并允许用户选择一个存储在'AvailableColours'属性中的子集。 – PTuckley
@ptuckley对不起,这是一个小错字。该物业是'AvailableColours'。我也对它进行了调整,以适应最初未包含在问题中的更多细节。 – hutchonoid
恐怕这对我来说还没有多大意义 - 答案中的模型是什么类型?在'for'循环声明中有对'Model.AvailableColours'的引用,但是在隐藏字段中引用'Model [i] .ID'? – PTuckley