2011-04-27 68 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部分。