您的位置:首页 > Web前端 > HTML

MVC通过扩展HtmlHelper实现RadioButtonList

2016-04-11 16:19 639 查看

RadioButtonList在Web页面应用非常广泛,在传统的ASP.NET aspx中系统自带有RadioButtonList控件,但是在MVC Razer中没有提供,下面介绍通过扩展HtmlHelper实现RadioButtonList的方法

 
 

 
public static class RRadioButtonListelper
{
public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string name)
{
return RadioButtonList(helper, name, helper.ViewData[name] as IEnumerable<SelectListItem>, new { });
}

public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList)
{
return RadioButtonList(helper, name, selectList, new { });
}

public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes)
{
IDictionary<string, object> HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

HtmlAttributes.Add("type", "radio");
HtmlAttributes.Add("name", name);

StringBuilder stringBuilder = new StringBuilder();
int i = 0;
int j = 0;
foreach (SelectListItem selectItem in selectList)
{
string id = string.Format("{0}{1}", name, j++);

IDictionary<string, object> newHtmlAttributes = HtmlAttributes.IDictionaryCopy();
newHtmlAttributes.Add("value", selectItem.Value);
newHtmlAttributes.Add("id", id);
var selectedValue = (selectList as SelectList).SelectedValue;
if (selectedValue == null)
{
if (i++ == 0)
newHtmlAttributes.Add("checked", null);
}
else if (selectItem.Value == selectedValue.ToString())
{
newHtmlAttributes.Add("checked", null);
}

TagBuilder tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes<string, object>(newHtmlAttributes);
string inputAllHtml = tagBuilder.ToString(TagRenderMode.SelfClosing);
stringBuilder.AppendFormat(@" {0}  <label for='{2}'>{1}</label>",
inputAllHtml, selectItem.Text, id);
}
return MvcHtmlString.Create(stringBuilder.ToString());

}
private static IDictionary<string, object> IDictionaryCopy(this IDictionary<string, object> ht)
{
Dictionary<string, object> _ht = new Dictionary<string, object>();

foreach (var p in ht)
{
_ht.Add(p.Key, p.Value);
}
return _ht;
}

public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
return RadioButtonListFor<TModel, TProperty>(htmlHelper, expression, selectList, null);
}

public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)
{
ModelState state;
if (expression == null)
{
throw new ArgumentNullException("expression");
}
if (selectList == null)
{
throw new ArgumentNullException("selectList");
}
ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

if (string.IsNullOrEmpty(fullHtmlFieldName))
{
throw new ArgumentException("name", "name");
}

StringBuilder builder = new StringBuilder();
int i = 0;
foreach(SelectListItem item in selectList)
{
TagBuilder tabBuilder = new TagBuilder("input");
tabBuilder.MergeAttribute("name", fullHtmlFieldName, true);
string id =string.Format("{0}_{1}", fullHtmlFieldName, i++);
tabBuilder.MergeAttribute("id", id, true);
tabBuilder.Attributes["type"] = "radio";
if (item.Value != null)
{
tabBuilder.Attributes["value"] = item.Value;
}
object selectedValue = null;
if (selectList is SelectList)
{
selectedValue = (selectList as SelectList).SelectedValue;
}
if (selectedValue != null && item.Value==selectedValue.ToString())
{
tabBuilder.Attributes["checked"] = "checked";
}
builder.AppendLine(string.Format(" {0}  <label for='{2}'>{1}</label>",
tabBuilder.ToString(TagRenderMode.Normal), item.Text, id));
}
TagBuilder tagBuilder = new TagBuilder("span")
{
InnerHtml = builder.ToString()
};
tagBuilder.MergeAttributes<string, object>(htmlAttributes);
if (htmlHelper.ViewData.ModelState.TryGetValue(fullHtmlFieldName, out state) && (state.Errors.Count > 0))
{
tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
}
tagBuilder.MergeAttributes<string, object>(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata));
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
}


参考资料:MVC通过扩展HtmlHelper实现RadioButtonList   http://www.studyofnet.com/news/1196.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  MVC ASP.NET