public static MvcHtmlString RadioButtonList(this HtmlHelper htmlHelper, string name, string codeCategory, RepeatDirection repeatDirection = RepeatDirection.Horizontal) { var codes = CodeManager.GetCodes(codeCategory); return ListControlUtil.GenerateHtml(name, codes, repeatDirection, "radio", null); } public static MvcHtmlString RadioButtonListFor(this HtmlHelper htmlHelper, Expression > expression, Collection codeCategory,CodeDescription selectCodeCategory, RepeatDirection repeatDirection = RepeatDirection.Horizontal) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression (expression, htmlHelper.ViewData); string name = ExpressionHelper.GetExpressionText(expression); string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); return ListControlUtil.GenerateHtml(fullHtmlFieldName, codeCategory, selectCodeCategory, repeatDirection, "radio", metadata.Model); } public static MvcHtmlString RadioButtonListFor (this HtmlHelper htmlHelper, Expression > expression, Collection codeCategory, RepeatDirection repeatDirection = RepeatDirection.Horizontal) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression (expression, htmlHelper.ViewData); string name = ExpressionHelper.GetExpressionText(expression); string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); return ListControlUtil.GenerateHtml(fullHtmlFieldName, codeCategory, repeatDirection, "radio", metadata.Model); } public static MvcHtmlString RadioButtonListForOne (this HtmlHelper htmlHelper, Expression > expression, IEnumerable selectList, string optionLabel, IDictionary htmlAttributes) { if (expression == null) { throw new ArgumentNullException("expression"); } string name = ExpressionHelper.GetExpressionText(expression); string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) { throw new ArgumentException("name"); } bool usedViewData = false; // If we got a null selectList, try to use ViewData to get the list of items. if (selectList == null) { selectList = htmlHelper.GetSelectData(fullName); usedViewData = true; } object defaultValue = htmlHelper.GetModelStateValue(fullName, typeof(string)); // If we haven't already used ViewData to get the entire list of items then we need to // use the ViewData-supplied value before using the parameter-supplied value. if (!usedViewData) { if (defaultValue == null) { defaultValue = htmlHelper.ViewData.Eval(fullName); } } if (defaultValue != null) { IEnumerable defaultValues = new[] { defaultValue }; IEnumerable values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture); HashSet selectedValues = new HashSet (values, StringComparer.OrdinalIgnoreCase); List newSelectList = new List (); foreach (SelectListItem item in selectList) { item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text); newSelectList.Add(item); } selectList = newSelectList; } #region TagBuilder table = new TagBuilder("table"); int i = 0; foreach (SelectListItem item in selectList) { // TagBuilder tr = new TagBuilder("tr"); i++; string id = string.Format("{0}_{1}", name, i); TagBuilder td = new TagBuilder("td"); td.InnerHtml = GenerateRadioHtml(name, id, item.Text, item.Value, item.Selected, htmlAttributes); tr.InnerHtml = td.ToString(); table.InnerHtml += tr.ToString(); } #endregion return new MvcHtmlString(table.ToString()); } private static IEnumerable GetSelectData(this HtmlHelper htmlHelper, string name) { object o = null; if (htmlHelper.ViewData != null) { o = htmlHelper.ViewData.Eval(name); } if (o == null) { throw new InvalidOperationException( "IEnumerable "); } IEnumerable selectList = o as IEnumerable ; if (selectList == null) { throw new InvalidOperationException( "IEnumerable "); } return selectList; } private static object GetModelStateValue(this HtmlHelper htmlHelper, string key, Type destinationType) { ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(key, out modelState)) { if (modelState.Value != null) { return modelState.Value.ConvertTo(destinationType, null /* culture */); } } return null; } private static string GenerateRadioHtml(string name, string id, string labelText, string value, bool isChecked, IDictionary htmlAttributes) { StringBuilder sb = new StringBuilder(); TagBuilder label = new TagBuilder("label"); label.MergeAttribute("for", id); label.SetInnerText(labelText); TagBuilder input = new TagBuilder("input"); input.GenerateId(id); input.MergeAttribute("name", name); input.MergeAttribute("type", "radio"); input.MergeAttribute("value", value); input.MergeAttributes(htmlAttributes); if (isChecked) { input.MergeAttribute("checked", "checked"); } sb.AppendLine(input.ToString()); sb.AppendLine(label.ToString()); return sb.ToString(); }
引用
public static class ListControlUtil { public static MvcHtmlString GenerateHtml(string name, Collectioncodes, RepeatDirection repeatDirection, string type, object stateValue) { TagBuilder table = new TagBuilder("table"); int i = 0; bool isCheckBox = type == "checkbox"; if (repeatDirection == RepeatDirection.Horizontal) { TagBuilder tr = new TagBuilder("tr"); if (codes == null) { return null; } foreach (var code in codes) { i++; string id = string.Format("{0}_{1}", name, i); TagBuilder td = new TagBuilder("td"); bool isChecked = false; if (isCheckBox) { IEnumerable currentValues = stateValue as IEnumerable ; isChecked = (null != currentValues && currentValues.Contains(code.Code)); } else { string currentValue = stateValue.ToString(); isChecked = (null != currentValue && code.Code == currentValue); } td.InnerHtml = GenerateRadioHtml(name, id, code.Description, code.Code, isChecked, type); tr.InnerHtml += td.ToString(); } table.InnerHtml = tr.ToString(); } else { foreach (var code in codes) { TagBuilder tr = new TagBuilder("tr"); i++; string id = string.Format("{0}_{1}", name, i); TagBuilder td = new TagBuilder("td"); bool isChecked = false; if (isCheckBox) { IEnumerable currentValues = stateValue as IEnumerable ; isChecked = (null != currentValues && currentValues.Contains(code.Code)); } else { string currentValue = stateValue as string; isChecked = (null != currentValue && code.Code == currentValue); } td.InnerHtml = GenerateRadioHtml(name, id, code.Description, code.Code, isChecked, type); tr.InnerHtml = td.ToString(); table.InnerHtml += tr.ToString(); } } return new MvcHtmlString(table.ToString()); } public static MvcHtmlString GenerateHtml(string name, Collection codes, CodeDescription selectCodeCategory, RepeatDirection repeatDirection, string type, object stateValue) { TagBuilder table = new TagBuilder("table"); int i = 0; bool isCheckBox = type == "checkbox"; if (repeatDirection == RepeatDirection.Horizontal) { TagBuilder tr = new TagBuilder("tr"); foreach (var code in codes) { i++; string id = string.Format("{0}_{1}", name, i); TagBuilder td = new TagBuilder("td"); bool isChecked = false; if (isCheckBox) { IEnumerable currentValues = stateValue as IEnumerable ; isChecked = (null != currentValues && currentValues.Contains(code.Code)); } else { string currentValue = selectCodeCategory.Code; isChecked = (null != currentValue && code.Code == currentValue); } td.InnerHtml = GenerateRadioHtml(name, id, code.Description, code.Code, isChecked, type); tr.InnerHtml += td.ToString(); } table.InnerHtml = tr.ToString(); } else { foreach (var code in codes) { TagBuilder tr = new TagBuilder("tr"); i++; string id = string.Format("{0}_{1}", name, i); TagBuilder td = new TagBuilder("td"); bool isChecked = false; if (isCheckBox) { IEnumerable currentValues = stateValue as IEnumerable ; isChecked = (null != currentValues && currentValues.Contains(code.Code)); } else { string currentValue = selectCodeCategory.Code; isChecked = (null != currentValue && code.Code == currentValue); } td.InnerHtml = GenerateRadioHtml(name, id, code.Description, code.Code, isChecked, type); tr.InnerHtml = td.ToString(); table.InnerHtml += tr.ToString(); } } return new MvcHtmlString(table.ToString()); } private static string GenerateRadioHtml(string name, string id, string labelText, string value, bool isChecked, string type) { StringBuilder sb = new StringBuilder(); TagBuilder label = new TagBuilder("label"); label.MergeAttribute("for", id); label.SetInnerText(labelText); TagBuilder input = new TagBuilder("input"); input.GenerateId(id); input.MergeAttribute("name", name); input.MergeAttribute("type", type); input.MergeAttribute("value", value); if (isChecked) { input.MergeAttribute("checked", "checked"); } sb.AppendLine(input.ToString()); sb.AppendLine(label.ToString()); return sb.ToString(); } }
控件所用自定义类CodeDescription
public class CodeDescription { public string Code { get; set; } public string Description { get; set; } public string Category { get; set; } public CodeDescription(string code, string description, string category) { this.Code = code; this.Description = description; this.Category = category; } }
使用方法初始化Controller
CollectionlistSex = new Collection (); listSex.Add(new CodeDescription( "1", "男", "Sex" )); listSex.Add(new CodeDescription("0", "女", "Sex")); ViewBag.SexItems = listSex; model.SexItems = listSex; model.SexSeltectItem = new CodeDescription("1", "男", "Sex");
前端使用
@Html.RadioButtonListFor(c => c.Sex, Model.SexItems,Model.SexSeltectItem)@Html.ValidationMessageFor(model => model.Sex)
控制器获取
obj.Sex = model.Sex;