问题描述
我想创造一些全球性的辅助功能。
我明白,我必须将它们放置在APP_ code一.cshtml文件。
我创建这个文件:
I want to create some global helper functions.I understood that i must place them in a .cshtml file in App_Code.I created this file:
@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
方法也不承认。
如何作出正确的?
The problem is that BeginForm
and AntiForgeryToken
methods are nor recognized.How to make it right?
PS:我使用.NET 4.5,asp.net mvc的4
PS: i am using .net 4.5, asp.net mvc 4
推荐答案
解决方案是在的HtmlHelper
对象作为参数传递到您的帮助:
The solution is to pass in the HtmlHelper
object as a parameter into your helper:
@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)
}
}
}
您也应该所需的 @using
语句添加到您的帮助文件进行扩展方法,如 BeginForm
工作
You should also add the required @using
statements to your helper file to make the extension methods like BeginForm
work:
@using System.Web.Mvc.Html
@using System.Web.Mvc
然后你需要打电话给你的helper方法是这样的:
And then you need to call your helper method something like this:
@MyHelpers.CreatePostForm(Html, "SomeAtion", "SomeContoller" , "SomeId")
这篇关于如何创建全局辅助功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!