gigi
gigi

Reputation: 3936

How to create global helper functions?

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

The problem is that BeginForm and AntiForgeryToken methods are nor recognized. How to make it right?

PS: i am using .net 4.5, asp.net mvc 4

Upvotes: 3

Views: 5852

Answers (2)

Rudey
Rudey

Reputation: 4975

You don't have to pass the HtmlHelper object as a parameter. Just put this in your .cshtml file residing in App_Code:

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

Other useful members are:

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

Upvotes: 1

nemesv
nemesv

Reputation: 139748

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

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

And then you need to call your helper method something like this:

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

Upvotes: 3

Related Questions