UrlHelper扩展方法不工作 [英] UrlHelper extension method not working

查看:486
本文介绍了UrlHelper扩展方法不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图扩展方法添加到我的MVC 2的项目没有成功几小时谷歌搜索和寻找在这里我在一个损失之后。我创建了一个全新的MVC 2项目,以确保有没有什么奇怪的我现有的项目,我依然面临着同样的问题。我敢肯定,这是我的情况不能见树不见林,所以任何帮助将大大AP preciated。这里是code的扩展方法。

I'm trying to add an extension method to my MVC 2 project without success and after several hours of googling and looking here I'm at a loss. I've created a brand new MVC 2 project to make sure there was not anything weird about my existing project and I'm still facing the same problem. I'm sure this is a situation of I "can't see the forest for the trees" so any help would be greatly appreciated. Here is the code for the extension method.

using System.Web.Mvc;

namespace ExtensionTest.Helper
{
    public static class UrlExtensions
    {
        public static string Image(this UrlHelper helper, string fileName)
        {
            return helper.Content("~/Content/Images/" + fileName);
        }

    }
}

和这里是在视图中code(默认情况下,一个新的MVC 2项目创建标准的家庭索引视图)

and here is the code in the view (standard home index view created by default for a new MVC 2 project)

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="ExtensionTest.Helper" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%= UrlHelper.Image("test") %>
    <h2><%: ViewData["Message"] %></h2>
    <p>
        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
    </p>
</asp:Content>

在设计模式下,当我输入UrlHelper,智能感知不显示我的扩展方法形象,如果我运行该项目,我得到了以下错误:

In design mode, when I type UrlHelper, intellisense does not show my extension method Image and if I run the project I get the following error:

CS0117: 'System.Web.Mvc.UrlHelper' does not contain a definition for 'Image'

起初我以为是不添加引用(import语句)一样简单,但不会出现这种情况。真正奇怪的事情对我来说,我可以在这同一个项目中添加扩展方法为对象的HtmlHelper没有问题。

At first I thought it was as simple as not adding a reference (Import statement), but that does not appear to be the case. The really weird thing to me is that I can add extension methods to the HtmlHelper object without issue in this same project.

在此先感谢提供任何帮助。

Thanks in advance for any help provided.

推荐答案

在.NET扩展方法应该在一个对象实例,而不是类本身(即使它们是静态的)被调用。

Extension methods in .NET should be invoked on an object instance and not on the class itself (even though they are static).

而不是:

<%= UrlHelper.Image("test") %>

尝试:

<%= Url.Image("test") %>

这篇关于UrlHelper扩展方法不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆