如何在Orchard中找到图像资源

时间:2015-02-16 12:17:42

标签: c# asp.net-mvc image url orchardcms

我想在MVC视图中获取图像资源的链接,该视图是Orchard模块的一部分。

谷歌搜索导致以下方法:

https://stackoverflow.com/a/9256515/3936440

并在视图中使用@Html.ResourceUrl()来获取资源URL。

我想知道ResourceUrl()来自哪里,因为它没有在MSDN中记录,我也不能在我的项目中使用它。

是否有人已经使用过这种方法,并且可以解释一下这里缺少什么?

更新

我明白了。以下代码与Orchard模块一起使用。

首先,您需要将资源清单添加到Orchard模块,如此

public class ResourceManifest : Orchard.UI.Resources.IResourceManifestProvider
{
  public void BuildManifests(Orchard.UI.Resources.ResourceManifestBuilder aBuilder)
  {
    Orchard.UI.Resources.ResourceManifest lManifest = aBuilder.Add();

    string lModulePath = "~/Modules/YourModuleName";

    lManifest.DefineResource("ProfilePicture", "User1").SetUrl(lModulePath + "/Images/User1.png");
  }
}

然后扩展Html对象:

// This class adds so called "extension methods" to class System.Web.Mvc.HtmlHelper
public static class HtmlHelperExtensions
{
  // This method retrieves the URL of a resource defined in ResourceManifest.cs via the Orchard resource management system
  public static string ResourceUrl(this System.Web.Mvc.HtmlHelper aHtmlHelper, string aResourceType, string aResourceName)
  {
    // note:
    //  resolving Orchard.UI.Resources.IResourceManager via work context of orchard because
    //    - calling System.Web.Mvc.DependencyResolver.Current.GetService() does not work as it always returns null at this point
    //    - constructor parameter injection is not allowed in static classes
    //    - setting the resource manager from another class that uses constructor parameter injection does not work as it causes a "circular component dependency "
    Orchard.WorkContext lWorkContext = Orchard.Mvc.Html.HtmlHelperExtensions.GetWorkContext(aHtmlHelper);

    Orchard.UI.Resources.IResourceManager lResourceManager = (Orchard.UI.Resources.IResourceManager)lWorkContext.Resolve<Orchard.UI.Resources.IResourceManager>();
    if (lResourceManager != null)
    {
      Orchard.UI.Resources.RequireSettings lSettings = new Orchard.UI.Resources.RequireSettings { Type = aResourceType, Name = aResourceName, BasePath = aResourceType };

      Orchard.UI.Resources.ResourceDefinition lResource = lResourceManager.FindResource(lSettings);
      if (lResource != null)
      {
        Orchard.UI.Resources.ResourceRequiredContext lContext = new Orchard.UI.Resources.ResourceRequiredContext { Resource = lResource, Settings = lSettings };

        string lAppBasePath = System.Web.HttpRuntime.AppDomainAppVirtualPath;

        return lContext.GetResourceUrl(lSettings, lAppBasePath);
      }
    }

    return null;
  }
}

然后你可以写:

<img src="@Html.ResourceUrl("ProfilePicture", "User1")" />
在Orchard模块视图中

以获取User1的适当图像链接。

我希望这会有所帮助。

1 个答案:

答案 0 :(得分:1)

ResourceUrl()是自定义HtmlHelper扩展程序。

您需要实现它的代码包含在您已链接的答案中。

您只需要创建一个包含方法代码的静态类。

Asp.net article on how to create custom html helpers

PS:确保您使用@using YourNamespace将名称空间导入视图,或将其添加到System.Web.Mvc.HtmlHelper类。