C# 封装HtmlHelper组件:BootstrapHelper

2019-12-30 13:35:50王冬梅

我们将pages节点的pageBaseType改成我们的WebViewPage


<system.web.webPages.razor>
 <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
 <pages pageBaseType="Extensions.BootstrapWebViewPage">
  <namespaces>
  <add namespace="System.Web.Mvc" />
  <add namespace="System.Web.Mvc.Ajax" />
  <add namespace="System.Web.Mvc.Html" />
  <add namespace="System.Web.Routing" />
  <add namespace="BootstrapHelper" />
  </namespaces>
 </pages>
 </system.web.webPages.razor>

然后编译,重新打开Index.cshtml。

bootstraphelper,htmlhelper

OK,可以找到Bootstrap对象了。我们将Index.cshtml里面写入如下内容:


@{
 Layout = null;
}
<!DOCTYPE html>
<html>
<head>
 <meta name="viewport" content="width=device-width" />
 <title>Index</title>
</head>
<body>
 <div> 
  @Html.Label("姓名")
  @Html.TextBox("a", "Jim")
  @Bootstrap.Label(null, "Bootstrap Label标签", null, null)
 </div>
</body>
</html>

运行看看效果:

bootstraphelper,htmlhelper

怎么还是报错呢?这个问题应该不难理解,因为在razor里面使用@调用后台变量和方法的时候也存在命名空间的概念,这个命名空间在哪里引用呢,还是在View文件夹里面的web.config里面,在system.web.webPages.razor节点下面存在namespace的节点,我们将自定义的Label()扩展方法所在的命名空间加进去即可。于是配置变成这样:


<system.web.webPages.razor>
 <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
 <pages pageBaseType="Extensions.BootstrapWebViewPage">
  <namespaces>
  <add namespace="System.Web.Mvc" />
  <add namespace="System.Web.Mvc.Ajax" />
  <add namespace="System.Web.Mvc.Html" />
  <add namespace="System.Web.Routing" />
  <add namespace="BootstrapHelper" />
  <add namespace="Extensions"/>
  </namespaces>
 </pages>
 </system.web.webPages.razor>

再次运行

bootstraphelper,htmlhelper