【问题标题】:Shifting @helper code to App_Code folder throwing error将@helper 代码转移到 App_Code 文件夹抛出错误
【发布时间】:2012-07-17 01:51:08
【问题描述】:

我有一个@heper pagination 函数。那就是有两个 View helper ViewBagUrl。 这个分页将被很多页面使用,所以我将代码从Views 文件夹转移 到App_Code 文件夹。 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>
     }   
}

但是现在当我运行应用程序时。它抛出错误

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

我是否需要导入任何命名空间或问题出在哪里?

我想做的方式是完美的吗?

【问题讨论】:

    标签: asp.net-mvc-3 razor


    【解决方案1】:

    实际上,您可以像这样从 App_Code 文件夹中的帮助程序访问 ViewBag:

    @helper buildLinks()
    {
        var p = (System.Web.Mvc.WebViewPage)PageContext.Page;
    
        var vb = p.ViewBag;
    
        /* vb is your ViewBag */
    }
    

    【讨论】:

    【解决方案2】:

    正如 Mark 所说,您应该将 UrlHelper 作为参数传递给您的助手:

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

    然后在视图中这样称呼它:

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

    【讨论】:

    • 达林,如果我在对@akakey 的回复的评论中发表的评论中可以从 RequestContext 中获取 URL,为什么还要传递 URL?
    • 我不想将 currentPage 作为参数传递。 @akakey 找到了更好的。
    • 见下面@akakey 答案,应该标记为正确答案
    【解决方案3】:

    如果您将助手移至 App_Code,则必须将 ViewBagUrlHelperHtmlHelper 传递给视图中的函数。

    例如

    App_code 中的 html 辅助函数

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

    在您看来,

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

    【讨论】:

    • 是的,你可以使用它,但你必须从视图中传递帮助器
    • 你能发布你想要达到的目标吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多