我有一个使用区域的MVC3 / Razor应用程序,以便我的视图位于以下位置:
/Areas/Areaname/Views/ControllerName/view.cshtml
现在,对于任何共享的部分内容,我必须将它们放在这里:
/Views/Shared/_sharedview.cshtml
我希望在此处提供我的共享观点:
/Areas/Shared/Views/_sharedvew.cshtml
有没有办法让视图引擎看到共享视图的默认位置以外的其他位置?
我在想这样的事情:
routes.MapRoute("Shared", "Areas/Shared/Views/{id}");
谢谢!
答案 0 :(得分:0)
我通常从VirtualPathProvider下载一个类
请点击此处了解更多信息:
http://coderjournal.com/2009/05/creating-your-first-mvc-viewengine/
然后在启动时注册:
HostingEnvironment.RegisterVirtualPathProvider(new EmbeddedViewPathProvider());
您不必处理范围之外的路径,因为您可以像在此嵌入式视图路径提供程序中那样在基本定义上传递函数:
public class EmbeddedViewPathProvider: VirtualPathProvider
{
static EmbeddedViewPathProvider()
{
ResourcePaths = new Dictionary<string, ViewResource>();
foreach (var resource in SettingsManager.Get<CoreSettings>().Assemblies.Select(assembly => new ViewResource
{
VirtualPath = "/views/embedded/" + assembly.ToLower(), AssemblyName = assembly
}))
{
AddResource(resource);
}
}
public static void AddResource(ViewResource assemblyResource)
{
ResourcePaths.Add(assemblyResource.VirtualPath, assemblyResource);
}
private static Dictionary<string, ViewResource> ResourcePaths { get; set; }
public bool IsAppResourcePath(string virtualPath)
{
var checkPath = VirtualPathUtility.ToAppRelative(virtualPath).ToLower();
return ResourcePaths.Any(resourcePath => checkPath.Contains(resourcePath.Key) && ResourceExists(resourcePath.Value, checkPath));
}
private static bool ResourceExists(ViewResource assemblyResource, string path)
{
var name = assemblyResource.GetFullyQualifiedTypeFromPath(path);
return Assembly.Load(assemblyResource.AssemblyName).GetManifestResourceNames().Any(s => s.ToLower().Equals(name));
}
public ViewResource GetResource(string virtualPath)
{
var checkPath = VirtualPathUtility.ToAppRelative(virtualPath).ToLower();
return (from resourcePath in ResourcePaths where checkPath.Contains(resourcePath.Key) select resourcePath.Value).FirstOrDefault();
}
public override bool FileExists(string virtualPath)
{
var exists = base.FileExists(virtualPath);
return exists || IsAppResourcePath(virtualPath);
}
public override VirtualFile GetFile(string virtualPath)
{
if (IsAppResourcePath(virtualPath) && !base.FileExists(virtualPath))
{
var resource = GetResource(virtualPath);
return new ViewResourceVirtualFile(virtualPath, resource);
}
return base.GetFile(virtualPath);
}
public override CacheDependency
GetCacheDependency(string virtualPath,
IEnumerable virtualPathDependencies,
DateTime utcStart)
{
if (IsAppResourcePath(virtualPath))
{
return null;
}
var dependencies = virtualPathDependencies.OfType<string>().Where(s => !s.ToLower().Contains("/views/embedded")).ToArray();
return base.GetCacheDependency(virtualPath, dependencies, utcStart);
}
public override string GetCacheKey(string virtualPath)
{
return null;
}
}