MVC通过UIHint和自定义视图显示RadioButtonList
在Product类中有一个显示删除状态的属性DelFlag,在编辑视图页,对于所有的删除状态以RadioButtonList显示出来,如果RadioButtonList选项的value值与当前model的DelFlag属性值相同,则勾选该选项,如图:
思路:
→在Views/Shared/EditorTemplates/RadioButtonList.chtml部分视图以RadioButtonList呈现所有删除状态。
→在编辑视图中,需要把有关删除状态,封装成List<SelectListItem>放在路由中传递给部分视图RadioButtonList.chtml
→在Product的DelFlag属性上,通过[UIHint("RadioButtonList")]指定该属性的显示视图
public class Product
{
[UIHint("RadioButtonList")]
public int? DelFlag { get; set; }
}
HomeController:
public class HomeController : Controller
{
public ActionResult Index()
{
return View( new Product(){DelFlag = 2});
}
}
Home/Index.cshtml视图:
其中,关于删除状态,封装成List<SelectListItem>,并通过路由传递给接收的部分视图。
@model MvcApplication2.Models.Product
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem(){Text = "正常使用",Value = "1"});
list.Add(new SelectListItem() { Text = "逻辑删除", Value = "2" });
list.Add(new SelectListItem() { Text = "物理删除", Value = "3" });
}
<style type="text/css">
ul{
list-style-type: none;
}
</style>
<h2>Index</h2>
@Html.EditorFor(model => model.DelFlag, new {lst = list})
Views/Shared/EditorTemplates/RadioButtonList.chtml部分视图:
@model int?
@{
var list = (List<SelectListItem>)ViewData["lst"];
}
<ul>
@foreach (var item in list)
{
<li>
@{
var radioId = ViewData.TemplateInfo.GetFullHtmlFieldId(item.Value); //DelFlag_1 DelFlag_2 DelFlag_3
var checkedCls =
(item.Value == Model.ToString() ? "Checked" : string.Empty);
//name=DelFlag 属性名称被保存在ViewData.TemplateInfo.HtmlFieldPrefix中
<input type="radio" id="@radioId" name="@ViewData.TemplateInfo.HtmlFieldPrefix" value="@item.Value" checked="@checkedCls"/>
<label for="@radioId">@item.Text</label>
}
</li>
}
</ul>