我建议你使用视图模型。请看下面这个例子:
namespace MvcApplication1.Controllers {
public class TheOption {
public string Id { get; set; }
public string Value { get; set; }
public bool? Checked { get; set; }
}
public class FooController : Controller {
//
// GET: /Foo/
public ActionResult Index() {
var options = new List<TheOption> {
new TheOption {Id = "One", Value = "The One"},
new TheOption {Id = "Two", Value = "The Two"},
new TheOption {Id = "Hundred", Value = "The Hundred"},
};
return View(options);
}
[HttpPost]
public ActionResult Index(List<TheOption> options) {
return View(options);
}
}
}
现在您需要为TheOption
模型创建编辑器模板。只需在 ~\Views\Shared\ 文件夹下创建名为EditorTemplates的文件夹即可。添加新视图作为编辑器模板。将此编辑器模板命名为与模型名称 ( TheOption
) 匹配。
这是~\Views\Shared\EditorTemplates\TheOption.cshtml的内容:
@model MvcApplication1.Controllers.TheOption
<div>
@Html.RadioButtonFor(m => m.Checked, true, new { id = Model.Id + "_selected" })
@Html.RadioButtonFor(m => m.Checked, false, new { id = Model.Id }) @Model.Value
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.Value)
</div>
现在转到您的主视图(Index.cshtml)并简单地输入以下代码:
@model System.Collections.Generic.List<MvcApplication1.Controllers.TheOption>
@using (Html.BeginForm()) {
@Html.EditorFor(m=>m)
<button type="submit">Save</button>
}
完毕!希望这可以帮助 :)