using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Linq.Expressions;using System.Web.Mvc;using System.Text;namespace MyJob.Helpers{ public static class HtmlHelperExt { public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string name, IEnumerableitems,string selectValue=null,RadioButtonListType type=0) { var selectList = new SelectList(items); return helper.RadioButtonList(name, selectList, selectValue,type); } /// /// /// /// /// /// /// 0:代表水平排列,1:代表垂直方向排列 ///public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string name, IEnumerable items, string selectValue=null, RadioButtonListType type = 0) { var sb = new StringBuilder(); foreach (var item in items) { var rbValue = item.Value ?? item.Text; var rbText = item.Text ?? item.Value; var rbId = name + "_" + rbValue; var radioTag = ""; if (String.IsNullOrEmpty(selectValue)) { if (item.Selected) radioTag = String.Format(" ", name, rbId, rbValue); else radioTag = String.Format(" ", name, rbId, rbValue); } else { if (rbValue.Trim() == selectValue.Trim()) radioTag = String.Format(" ", name, rbId, rbValue); else radioTag = String.Format(" ", name, rbId, rbValue); } var labelTag = new TagBuilder("label"); labelTag.MergeAttribute("for", rbId); labelTag.MergeAttribute("id", rbId + "_label"); labelTag.InnerHtml = rbText; sb.Append(radioTag.ToString() + labelTag.ToString()); if (type == RadioButtonListType.V) sb.Append(" "); } return MvcHtmlString.Create(sb.ToString()); } }}
调用1
@Html.RadioButtonList(m=>m.UserType,new [] { new SelectListItem { Text = "个人", Value = "Personal", Selected = true }, new SelectListItem { Text = "企业", Value = "Company" }})
调用2
@Html.RadioButtonList(m=>m.UserType,new [] { new SelectListItem { Text = "个人", Value = "Personal", Selected = true }, new SelectListItem { Text = "企业", Value = "Company" }},"个人",0)
其实 复选也一样! checkBoxlist