Lov*_*own 9 c# asp.net asp.net-mvc razor asp.net-mvc-4
我正在开发一个MVC应用程序,其中Model类Item具有一个List<Colour>名为AvailableColoursproperty的属性.
AvailableColours是用户定义的Colour类子集.我想显示所有Colour的复选框列表实例,并提交时,AvailableColours是一个List<Colour>包含检查Colour类.
在MVC中执行此操作的最佳方法是什么?
编辑:我的代码到目前为止,虽然我觉得这不是最MVC的方法!
模型
public class Item
{
public int ID { get; set; }
public List<Colour> AvailableColours { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
视图
@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" />
}
Run Code Online (Sandbox Code Playgroud)
调节器
[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();
}
}
Run Code Online (Sandbox Code Playgroud)
hut*_*oid 29
楷模
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; }
}
Run Code Online (Sandbox Code Playgroud)
注意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" />
}
Run Code Online (Sandbox Code Playgroud)
请注意foreach的for循环启用模型绑定和隐藏字段以允许将值发布回控制器
控制器帖子
[HttpPost]
public ActionResult Create(Item model)
{
//All the selected are available in AvailableColours
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64513 次 |
| 最近记录: |