【问题标题】:How to create global helper functions?如何创建全局辅助函数?
【发布时间】:2012-10-10 18:12:31
【问题描述】:

我想创建一些全局辅助函数。 我知道我必须将它们放在 App_Code 中的 .cshtml 文件中。 我创建了这个文件:

@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)   
        }
    }
}

问题是 BeginFormAntiForgeryToken 方法也无法识别。 怎么弄好?

PS:我使用的是 .net 4.5,asp.net mvc 4

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

解决方案是将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)   
        }
    }
}

您还应该将所需的@using 语句添加到您的帮助文件中,以使BeginForm 等扩展方法起作用:

@using System.Web.Mvc.Html
@using System.Web.Mvc

然后你需要像这样调用你的辅助方法:

@MyHelpers.CreatePostForm(Html, "SomeAtion", "SomeContoller" , "SomeId")

【讨论】:

  • 我仍然无法访问 html 参数上的那些方法。其次,我可以在那个cshtml中使用Html。问题在于那些扩展方法(BeginForm、AntiForgeryToken)。
  • 这些都是扩展方法你在帮助文件的顶部添加了所需的使用吗? @using System.Web.Mvc.Html @using System.Web.Mvc
  • 我不太喜欢将Html 作为输入。但是添加this 来尝试进行扩展对我的助手不起作用。还有其他方法吗? (除了一个更难构建的真正的扩展类。)
  • @ashes999 没有别的办法。如果你想要一个全局帮助方法并使用Html,那么你需要传入一个HtmlHelper。或者您需要创建一个适当的扩展类并创建一个常规的HtmlHelper 扩展。
  • 您不必将任何内容传递给全局帮助函数。见my answer
【解决方案2】:

您不必将HtmlHelper 对象作为参数传递。只需将其放在 App_Code 中的 .cshtml 文件中即可:

@functions {
    private new static HtmlHelper<dynamic> Html => ((WebViewPage)WebPageContext.Current.Page).Html;
}

其他有用的成员有:

private static UrlHelper Url => ((WebViewPage)WebPageContext.Current.Page).Url;
private static ViewContext ViewContext => ((WebViewPage)WebPageContext.Current.Page).ViewContext;

【讨论】:

    猜你喜欢
    • 2015-12-01
    • 2016-02-06
    • 2016-03-14
    • 2011-02-18
    • 1970-01-01
    • 2022-01-08
    • 2023-04-01
    • 1970-01-01
    • 2020-10-21
    相关资源
    最近更新 更多