C# 将MVC视图管线值映射到物理路径
假设我有一个路径的路由值,该路径有一个视图,如C# 将MVC视图管线值映射到物理路径,c#,asp.net-mvc-3,routes,asp.net-mvc-routing,C#,Asp.net Mvc 3,Routes,Asp.net Mvc Routing,假设我有一个路径的路由值,该路径有一个视图,如 new { controller = "Home", action = "Index" } 如何将其映射到~/Views/Home/Index.cshtml 我知道并不是所有的视图都必须有一个动作,也不是所有的动作都必须返回一个视图,所以这可能是一个问题 更新: 也许是这样的: IView view = ViewEngines.Engines.FindView(ControllerContext, "Index").View; v
new
{
controller = "Home",
action = "Index"
}
如何将其映射到~/Views/Home/Index.cshtml
我知道并不是所有的视图都必须有一个动作,也不是所有的动作都必须返回一个视图,所以这可能是一个问题
更新:
也许是这样的:
IView view = ViewEngines.Engines.FindView(ControllerContext, "Index").View;
view.GetViewPath();
但是这允许我指定一个控制器,而不是假设我想要使用我的controllerContext(或者甚至可能为我想要的控制器(字符串)模拟controllerContext)。从RazorViewEngine.cs(mvc3源代码中),视图的搜索路径如下(假设razor):
{1} 引用控制器routevalue,{0}是视图名称(不是routevalue的一部分)
您可以搜索这些位置以尝试查找与您的条件匹配的视图,但您还需要了解您正在进行的假设数量…即视图与操作具有相同的名称(默认情况下为是,但如果在控制器操作的“视图调用”中指定了视图名称,则不需要).您已经提到了一些其他假设,我是这样做的:
private string GetPhysicalPath(string viewName, string controller)
{
ControllerContext context = CloneControllerContext();
if (!controller.NullOrEmpty())
{
context.RouteData.Values["controller"] = controller;
}
if (viewName.NullOrEmpty())
{
viewName = context.RouteData.GetActionString();
}
IView view = ViewEngines.Engines.FindView(viewName, context).View;
string physicalPath = view.GetViewPath();
return physicalPath;
}
GetViewPath
的扩展方法是:
public static string GetViewPath(this IView view)
{
BuildManagerCompiledView buildManagerCompiledView = view as BuildManagerCompiledView;
if (buildManagerCompiledView == null)
{
return null;
}
else
{
return buildManagerCompiledView.ViewPath;
}
}
private ControllerContext CloneControllerContext()
{
ControllerContext context = new ControllerContext(Request.RequestContext, this);
return context;
}
而CloneControllerContext
是:
public static string GetViewPath(this IView view)
{
BuildManagerCompiledView buildManagerCompiledView = view as BuildManagerCompiledView;
if (buildManagerCompiledView == null)
{
return null;
}
else
{
return buildManagerCompiledView.ViewPath;
}
}
private ControllerContext CloneControllerContext()
{
ControllerContext context = new ControllerContext(Request.RequestContext, this);
return context;
}
我不明白。MVC内置路由系统有什么问题?内置路由系统很好,但我需要将
viewName
/controller
对转换回物理路径,以简化呈现局部视图的方法所采用的参数,而不必传递完整的物理路径,现在我只需通过viewName
和controller
名称。您假设视图与您在此处发布的答案中的操作具有相同的名称:viewName=context.RouteData.GetActionString();如果您返回视图(),则这不是假设任何内容,这是Mvc自己的约定
如果您得到了映射到所请求操作的视图,我需要类似的东西。从未听说过.NullOrEmpty()
方法!只是字符串的语法糖。IsNullOrEmpty
,它是一个扩展方法。这是一个隐藏得很好的知识点。