Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 835
Rajan Rawal Avatar asked Nov 29 '22 14:11

Rajan Rawal


2 Answers

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 */
}
like image 76
akakey Avatar answered Dec 10 '22 22:12

akakey


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)
like image 34
Darin Dimitrov Avatar answered Dec 10 '22 23:12

Darin Dimitrov