在asp.net mvc 中每一个Html控件都返回了MvcHtmlString ,他继承了HtmlString。下面自定义一个关于显示男女性别的自定义Html控件,使在创建页面时,可以直接调用该自定义的Html控件。可以查看其他的Html控件返回的是HtmlHelper,所以自定义的时候也要返回相同的类型直接在Controls文件夹下建立要自定义的html控件代码如下:
1 using System.Web.Mvc; 2 using System.Text; 3 4 namespace System.Web.Mvc.Html 5 { 6 /// <summary> 7 /// 显示男女性别自定义控件 8 /// </summary> 9 public static class LabelGenderExtensions 10 { 11 /// <summary> 12 /// 获取值时:value值为1表示男,value值为2表示女 13 /// 默认选中男 14 /// </summary> 15 /// <param name="helper"></param> 16 /// <returns></returns> 17 public static MvcHtmlString LabelGender(this HtmlHelper helper) 18 { 19 StringBuilder str = new StringBuilder(); 20 str.Append("<input type='radio' name='sex' value=1 checked='checked'></input>"); 21 str.AppendFormat("<label for='{0}'>{1}</label>", "man", "男"); // 显示男性值 22 str.Append("<input type='radio' name='sex' value=2 ></input>"); 23 str.AppendFormat("<label for='{0}'>{1}</label>", "female", "女"); // 显示女性值 24 return new MvcHtmlString(str.ToString()); 25 } 26 } 27 }
此类要返回的value值也可以根据参数的方式传入
在页面中只需调用: @Html.LabelGender()
显示如图:
注意事项:1、注意创建类的命名空间要与本身的@Html保持一致
2、创建的类须为静态类,命名规则一般后缀为Extensions
能对HtmlHelper控件进行扩展,为建立自己的html标签提供了很大的方便。