Asp.net mvc 如何创建全局辅助函数?
我想创建一些全局辅助函数。 我知道我必须将它们放在App_代码中的.cshtml文件中。 我创建了这个文件:Asp.net mvc 如何创建全局辅助函数?,asp.net-mvc,Asp.net Mvc,我想创建一些全局辅助函数。 我知道我必须将它们放在App_代码中的.cshtml文件中。 我创建了这个文件: @helper CreatePostForm(string action, string controller, string id, params string[] hiddens) { using (BeginForm(action, controller, System.Web.Mvc.FormMethod.Post, new { id = id }))
@helper CreatePostForm(string action, string controller, string id, params string[] hiddens)
{
using (BeginForm(action, controller, System.Web.Mvc.FormMethod.Post, new { id = id }))
{
@Html.AntiForgeryToken()
foreach(string hidden in hiddens)
{
@Html.Hidden(hidden)
}
}
}
问题是,BeginForm
和AntiForgeryToken
方法都不被识别。
如何使它正确
PS:我正在使用.net 4.5、asp.net mvc 4解决方案是将
HtmlHelper
对象作为参数传递到您的帮助程序中:
@helper CreatePostForm(HtmlHelper html,
string action, string controller, string id,
params string[] hiddens)
{
using (html.BeginForm(action, controller, FormMethod.Post, new { id = id }))
{
@html.AntiForgeryToken()
foreach(string hidden in hiddens)
{
@html.Hidden(hidden)
}
}
}
您还应该使用语句将所需的@添加到帮助文件中,以使扩展方法(如BeginForm
工作):
@using System.Web.Mvc.Html
@using System.Web.Mvc
然后您需要调用助手方法,如下所示:
@MyHelpers.CreatePostForm(Html, "SomeAtion", "SomeContoller" , "SomeId")
您不必将HtmlHelper
对象作为参数传递。只需将其放入驻留在App_代码中的.cshtml文件中:
@functions {
private new static HtmlHelper<dynamic> Html => ((WebViewPage)WebPageContext.Current.Page).Html;
}
我仍然无法访问html参数上的那些方法。其次,我可以在cshtml中使用Html。问题是这些扩展方法(BeginForm、AntiForgeryToken)都有问题。这些都是扩展方法。您是否在帮助文件的顶部添加了所需的using@usingsystem.Web.Mvc.Html@usingsystem.Web.Mvc
我真的不喜欢将Html
作为输入传递。但是添加此
以尝试进行扩展对我的助手不起作用。还有别的办法吗?(除了更难构建的真正的扩展类之外。)@ashes999没有其他方法。如果您想要一个全局帮助器方法并使用Html
,那么您需要传入HtmlHelper
。或者您需要创建一个适当的扩展类并创建一个常规的HtmlHelper
扩展。您不必向全局帮助函数传递任何内容。请参阅。对于那些需要ASP.NET Core中的全局帮助函数的人,我在这里提供了一个可能的解决方案:
private static UrlHelper Url => ((WebViewPage)WebPageContext.Current.Page).Url;
private static ViewContext ViewContext => ((WebViewPage)WebPageContext.Current.Page).ViewContext;