2011-04-27 75 views
9

这是我的HTML帮助的样子:问题认识HTML辅助3剃刀

namespace WebApp.WebUI 
{ 
    public static class HtmlExtensions 
    { 

      public static MvcHtmlString GenerateCaptcha(this HtmlHelper helper, string theme) 
      { 
       string publicKey = ConfigurationManager.AppSettings["CaptchaKey_Public"]; 
       string privateKey = ConfigurationManager.AppSettings["CaptchaKey_Private"]; 
       var captchaControl = new Recaptcha.RecaptchaControl 
         { 
          ID = "recaptcha", 
          Theme = theme, 
          PublicKey = publicKey, 
          PrivateKey = privateKey 
         }; 

       var htmlWriter = new HtmlTextWriter(new StringWriter()); 

       captchaControl.RenderControl(htmlWriter); 

       return new MvcHtmlString(htmlWriter.InnerWriter.ToString()); 
      } 

    } 
} 

我试图使用它在这样的观点:

@{ 
     ViewBag.Title = "Register"; 
    } 
    @model WebApp.WebUI.ViewModel.RegisterModel 

    @using (Html.BeginForm("Register", "Auth", FormMethod.Post, new { Id = "ERForm" })) 
    { 
     @Html.GenerateCaptcha("clean") 
    } 

它给了我这个错误:

CS1061: 'System.Web.Mvc.HtmlHelper<WebApp.WebUI.ViewModel.RegisterModel>' does not contain a definition for 'GenerateCaptcha' and no extension method 'GenerateCaptcha' accepting a first argument of type 'System.Web.Mvc.HtmlHelper<WebApp.WebUI.ViewModel.RegisterModel>' could be found (are you missing a using directive or an assembly reference?)

我在做什么错。我的名字空间是正确的。您Razor视图顶部

@using WebApp.WebUI 

:它不会在智能感知露面@Html

回答

17

您可以添加。

如果你想重用许多不同意见之间的这种帮助,以避免每次添加使用条款的,你可以把它添加到~/Views/web.config文件的<namespaces>部分:

<system.web.webPages.razor> 
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> 
    <pages pageBaseType="System.Web.Mvc.WebViewPage"> 
     <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="WebApp.WebUI" /> 
     </namespaces> 
    </pages> 
</system.web.webPages.razor> 

这样做后请务必重新编译并重新开启Intellisense的Razor视图,以便有时间拿起它。

+0

我应该能够添加的命名空间中,而不是使用@using WebApp.WebUI吧? – 2011-04-27 18:50:21

+0

你们每个人都有没有运气让剃刀视图中的本地使用指令无法使用?这对我很有用,但是我仍然无法在全球范围内使用它(没有@using和@Html,)。 – JaJ 2011-09-30 22:28:28

2

像达林说的,但是,为了全局使用它,你可能需要将它添加到〜/ Views/web.config和〜/ web.config部分。