在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})
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
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>
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }