4

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?

Rajan Rawal
  • 6,171
  • 6
  • 40
  • 62

3 Answers3

13

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 */
}
akakey
  • 231
  • 2
  • 7
  • this answer is the cleanest. I don't know why it wasn't selected as such. For completeness, the @Url can be accessed as shown here: http://stackoverflow.com/questions/4522807/how-do-i-use-urlhelper-from-within-a-razor-helper – ekkis Dec 22 '13 at 23:36
4

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

Ex.

html helper function in App_code

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

From your view,

@SomeFunc("..", Html) // passing the html helper
VJAI
  • 32,167
  • 23
  • 102
  • 164
4

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)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928