这是我的Html助手的样子:
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?)
我做错了什么。我的命名空间是正确的。它不会出现在@Html
答案 0 :(得分:17)
您可以添加:
@using WebApp.WebUI
位于Razor视图的顶部。
如果你想在许多不同的视图中重用这个帮助器,以避免每次添加using子句,你可以将它添加到<namespaces>
文件的~/Views/web.config
部分:
<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>
执行此操作后,请确保重新编译并重新打开智能感知的Razor视图,以便有时间进行提取。
答案 1 :(得分:2)
就像Darin所说,但是为了在全局使用它,你可能需要将它添加到〜/ Views / web.config和〜/ web.config部分。
答案 2 :(得分:1)
要让html助手全球工作,请按照Darin Dimitrov的回答。完成后,关闭.cshtml视图并重新打开它,intellisense开始工作。
参考:Razor - mvc 3 - Namespace to web.config works but intellisense does not recognize extension
答案 3 :(得分:0)
对我来说,我使用的是Nopcommerce,必须添加using语句@using Nop.Web.Framework.Security.Captcha