Shifting @helper code to App_Code folder throwing error

I have a @heper pagination function. That is having two View helper ViewBag and Url. This pagination is going to be used by so many pages so i shift the code from Views folder to App_Code folder. Code inside App_Code/Helper.cshtml

@helper buildLinks(int start, int end, string innerContent)
     for (int i = start; i <= end; i++)
         <a class="@(i == ViewBag.CurrentPage ? "current" : "")" href="@Url.Action("index", "country", new { page = i })">@(innerContent ?? i.ToString())</a>

But now when I run the app. it throws error

error CS0103:The name 'ViewBag' does not exist in the current context
error CS0103:The name 'Url' does not exist in the current context

Do I need to import any namespace or where the problem is?

The way I want to do is perfect?


As Mark said, you should pass the UrlHelper as parameter to your helper:

@helper buildLinks(int start, int end, int currentPage, string innerContent, System.Web.Mvc.UrlHelper url)
     for (int i = start; i <= end; i++)
         <a class="@(i == currentPage ? "current" : "")" href="@url.Action("index", "country", new { page = i })">@(innerContent ?? i.ToString())</a>

and then call it like this fomr a view:

@Helper.buildLinks(1, 10, ViewBag.CurrentPage, "some text", Url)

Well actually you can access ViewBag from helpers inside App_Code folder like this:

@helper buildLinks()
    var p = (System.Web.Mvc.WebViewPage)PageContext.Page;

    var vb = p.ViewBag;

    /* vb is your ViewBag */

If you moved your helpers to App_Code then you have to pass the ViewBag, UrlHelper, HtmlHelper to the functions from your views.


html helper function in App_code

@helper SomeFunc(System.Web.Mvc.HtmlHelper Html)

From your view,

@SomeFunc("..", Html) // passing the html helper

Need Your Help

getting special characters in mysql

php mysql utf-8

I'm at begginner level of mysql, doing transition from access to mysql

Use of Google Fit Api

android google-fit google-fit-sdk

I am going to develop Health Application on Android Platform.which read data from wearable device and update on server.