具有对象列表作为属性的MVC模型 [英] MVC Model with a list of objects as property
问题描述
我正在研究Model类Item
具有名为AvailableColours
的List<Colour>
作为属性的MVC应用程序.
I am working on an MVC application where the Model class Item
has a List<Colour>
named AvailableColours
as a property.
AvailableColours
是Colour
类的用户定义子集.我想在复选框列表中显示所有Colour
实例,并且提交后,AvailableColours
是包含已检查的Colour
类的List<Colour>
.
AvailableColours
is a user defined subset of Colour
classes. I would like to display all Colour
instances in a check box list, and when submitted, AvailableColours
is a List<Colour>
containing the checked Colour
classes.
在MVC中执行此操作的最佳方法是什么?
What is the best way to do this in MVC?
到目前为止,我的代码,尽管我觉得这不是最MVC风格的方法!
My code so far, although I feel this is not the most MVC-ish way to do it!
模型
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();
}
}
推荐答案
模型
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
属性
查看循环
@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" />
}
请注意,在foreach的for循环中启用了模型绑定,并在隐藏字段中允许将值回传给控制器
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
管制员职位
[HttpPost]
public ActionResult Create(Item model)
{
//All the selected are available in AvailableColours
return View(model);
}
这篇关于具有对象列表作为属性的MVC模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!