这是aspx页面中的用法
<%= Html.RadioButtonListFor(m => m.GenderRadioButtonList)%>
这是视图模型
public class HomePageViewModel { public enum GenderType { Male, Female } public RadioButtonListViewModelGenderRadioButtonList { get; set; } public HomePageViewModel() { GenderRadioButtonList = new RadioButtonListViewModel { Id = "Gender", SelectedValue = GenderType.Male, ListItems = new List > { new RadioButtonListItem {Text = "Male", Value = GenderType.Male}, new RadioButtonListItem {Text = "Female", Value = GenderType.Female} } }; } }
这是用于单选按钮列表的视图模型
public class RadioButtonListViewModel{ public string Id { get; set; } private T selectedValue; public T SelectedValue { get { return selectedValue; } set { selectedValue = value; UpdatedSelectedItems(); } } private void UpdatedSelectedItems() { if (ListItems == null) return; ListItems.ForEach(li => li.Selected = Equals(li.Value, SelectedValue)); } private List > listItems; public List > ListItems { get { return listItems; } set { listItems = value; UpdatedSelectedItems(); } } } public class RadioButtonListItem { public bool Selected { get; set; } public string Text { get; set; } public T Value { get; set; } public override string ToString() { return Value.ToString(); } }
这是RadioButtonListFor的扩展方法
public static class HtmlHelperExtensions { public static string RadioButtonListFor(this HtmlHelper htmlHelper, Expression >> expression) where TModel : class { return htmlHelper.RadioButtonListFor(expression, null); } public static string RadioButtonListFor (this HtmlHelper htmlHelper, Expression >> expression, object htmlAttributes) where TModel : class { return htmlHelper.RadioButtonListFor(expression, new RouteValueDictionary(htmlAttributes)); } public static string RadioButtonListFor (this HtmlHelper htmlHelper, Expression >> expression, IDictionary htmlAttributes) where TModel : class { var inputName = GetInputName(expression); RadioButtonListViewModel radioButtonList = GetValue(htmlHelper, expression); if (radioButtonList == null) return String.Empty; if (radioButtonList.ListItems == null) return String.Empty; var divTag = new TagBuilder("div"); divTag.MergeAttribute("id", inputName); divTag.MergeAttribute("class", "radio"); foreach (var item in radioButtonList.ListItems) { var radioButtonTag = RadioButton(htmlHelper, inputName, new SelectListItem{Text=item.Text, Selected = item.Selected, Value = item.Value.ToString()}, htmlAttributes); divTag.InnerHtml += radioButtonTag; } return divTag + htmlHelper.ValidationMessage(inputName, "*"); } public static string GetInputName (Expression > expression) { if (expression.Body.NodeType == ExpressionType.Call) { var methodCallExpression = (MethodCallExpression)expression.Body; string name = GetInputName(methodCallExpression); return name.Substring(expression.Parameters[0].Name.Length + 1); } return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1); } private static string GetInputName(MethodCallExpression expression) { // p => p.Foo.Bar().Baz.ToString() => p.Foo OR throw... var methodCallExpression = expression.Object as MethodCallExpression; if (methodCallExpression != null) { return GetInputName(methodCallExpression); } return expression.Object.ToString(); } public static string RadioButton(this HtmlHelper htmlHelper, string name, SelectListItem listItem, IDictionary htmlAttributes) { var inputIdSb = new StringBuilder(); inputIdSb.Append(name) .Append("_") .Append(listItem.Value); var sb = new StringBuilder(); var builder = new TagBuilder("input"); if (listItem.Selected) builder.MergeAttribute("checked", "checked"); builder.MergeAttribute("type", "radio"); builder.MergeAttribute("value", listItem.Value); builder.MergeAttribute("id", inputIdSb.ToString()); builder.MergeAttribute("name", name + ".SelectedValue"); builder.MergeAttributes(htmlAttributes); sb.Append(builder.ToString(TagRenderMode.SelfClosing)); sb.Append(RadioButtonLabel(inputIdSb.ToString(), listItem.Text, htmlAttributes)); sb.Append("
"); return sb.ToString(); } public static string RadioButtonLabel(string inputId, string displayText, IDictionaryhtmlAttributes) { var labelBuilder = new TagBuilder("label"); labelBuilder.MergeAttribute("for", inputId); labelBuilder.MergeAttributes(htmlAttributes); labelBuilder.InnerHtml = displayText; return labelBuilder.ToString(TagRenderMode.Normal); } public static TProperty GetValue (HtmlHelper htmlHelper, Expression > expression) where TModel : class { TModel model = htmlHelper.ViewData.Model; if (model == null) { return default(TProperty); } Func func = expression.Compile(); return func(model); } }
创建3个单选按钮的MVC 3示例,其中包含验证以确保选项为1.如果表单未通过验证(例如,在其他字段上),则在重新表示表单时预先选择所选的无线电选项.
视图
@Html.RadioButtonForSelectList(m => m.TestRadio, Model.TestRadioList) @Html.ValidationMessageFor(m => m.TestRadio)
模型
public class aTest { public Int32 ID { get; set; } public String Name { get; set; } } public class LogOnModel { public IEnumerableTestRadioList { get; set; } [Required(ErrorMessage="Test Error")] public String TestRadio { get; set; } [Required] [Display(Name = "User name")] public string UserName { get; set; } }
控制器动作
public ActionResult LogOn() { Listlist = new List (); list.Add(new aTest() { ID = 1, Name = "Line1" }); list.Add(new aTest() { ID = 2, Name = "Line2" }); list.Add(new aTest() { ID = 3, Name = "Line3" }); SelectList sl = new SelectList(list, "ID", "Name"); var model = new LogOnModel(); model.TestRadioList = sl; return View(model); } [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { .... } // If we got this far, something failed, redisplay form List list = new List (); list.Add(new aTest() { ID = 1, Name = "Line1" }); list.Add(new aTest() { ID = 2, Name = "Line2" }); list.Add(new aTest() { ID = 3, Name = "Line3" }); SelectList sl = new SelectList(list, "ID", "Name"); model.TestRadioList = sl; return View(model); }
这是扩展名:
public static class HtmlExtensions { public static MvcHtmlString RadioButtonForSelectList( this HtmlHelper htmlHelper, Expression > expression, IEnumerable listOfValues) { var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); var sb = new StringBuilder(); if (listOfValues != null) { foreach (SelectListItem item in listOfValues) { var id = string.Format( "{0}_{1}", metaData.PropertyName, item.Value ); var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString(); sb.AppendFormat( " {2}", id, HttpUtility.HtmlEncode(item.Text), radio ); } } return MvcHtmlString.Create(sb.ToString()); } }