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?
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 */
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With