【问题标题】:The name 'Url' does not exist in the current context error当前上下文错误中不存在名称“Url”
【发布时间】:2013-06-01 21:41:02
【问题描述】:

我有一个 MVC4 项目,我正在尝试为其创建一个助手。我添加了一个名为“App_Code”的文件夹,并在该文件夹中添加了一个名为 MyHelpers.cshtml 的文件。以下是该文件的全部内容:

@helper MakeButton(string linkText, string actionName, string controllerName, string iconName, string classes) {
    <a href='@Url.Action(linkText,actionName,controllerName)' class="btn @classes">Primary link</a>
}

(我知道有一些未使用的参数,等我修好之后再处理)

我“清理”并构建了解决方案,没有错误。

在使用助手的页面中,我添加了这段代码。

@MyHelpers.MakeButton("Back","CreateOffer","Merchant","","btn-primary")

当我尝试运行项目时,我收到以下错误:

编译器错误消息:CS0103:名称“Url”不存在于 当前上下文

我似乎找不到正确的写法——我做错了什么?与我在网上看到的示例相比,这似乎是正确的?

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-4 view-helpers


【解决方案1】:

正如 JeffB 的链接所示,您的帮助文件无权访问 UrlHelper 对象。

这是一个修复示例:

@helper MakeButton(string linkText, string actionName,
    string controllerName, string iconName, string classes) {

    System.Web.Mvc.UrlHelper urlHelper =
        new System.Web.Mvc.UrlHelper(Request.RequestContext);
    <a href='@urlHelper.Action(linkText,actionName,controllerName)'
        class="btn @classes">Primary link</a>
}

【讨论】:

    【解决方案2】:

    我为我的助手创建了一个基类:

    using System.Web.WebPages;
    using System.Web.Mvc;
    
    namespace MyProject
    {
        public class HelperBase : HelperPage
        {
            public static new HtmlHelper Html
            {
                get { return ((WebViewPage)WebPageContext.Current.Page).Html; }
            }
            public static System.Web.Mvc.UrlHelper Url
            {
                get { return ((WebViewPage)WebPageContext.Current.Page).Url; }
            }
        }
    }
    

    然后在我的助手中(以你的为例):

    @inherits MyProject.HelperBase
    @using System.Web.Mvc
    @using System.Web.Mvc.Html
    
    @helper MakeButton(string linkText, string actionName, string controllerName, string iconName, string classes) {
        <a href='@Html.ActionLink(linkText,actionName,controllerName)' class="btn @classes">Primary link</a>
    }
    

    另外,你确定你不是要使用@Html.ActionLink(通过LinkExtensions)而不是@Url.Action吗?后者似乎没有linkText, actionName, controllerName 过载,前者有?

    【讨论】:

    • 你的基类很棒!正是我需要的,谢谢。
    • 是的,完美,正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 2019-01-16
    相关资源
    最近更新 更多