Mvc_扩展@html
HtmlHelper的一个实例,它被定义在System.Web.Mvc名称空间下的WebViewPage类,即它对于所有MVC页面都可用)建立好扩展方法后:
@Html.CreateGanderRadioButton() namespace Web.Helper { public static class ExtendHtml { public static MvcHtmlString CreateGanderRadioButton(this System.Web.Mvc.HtmlHelper html) { StringBuilder str = new StringBuilder(); str.Append("<input type='radio' value=1 name='gander'>男"); str.Append("<input type='radio' value=0 name='gander'>女"); return MvcHtmlString.Create(str.ToString()); } } }
注意,它所在的类必须是public static的,也就是说,它的扩展方法本身也是public static的。
对于,直接在页面上使用我们的方法,还是差了一步,那就是,要在web.config里把Web.Helper名称
空间加上,页面上才能访问的到:
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
<add namespace="Web.Helper" />
</namespaces>