假设我有一个具有 View 的路径的路由值,例如
new
{
controller = "Home",
action = "Index"
}
如何将其映射到 ~/Views/Home/Index.cshtml
?
我知道并非所有 View 都必须执行操作,也并非所有操作都必须返回 View ,因此这可能会成为一个问题。
更新:
也许是这样的:
IView view = ViewEngines.Engines.FindView(ControllerContext, "Index").View;
view.GetViewPath();
但这允许我指定一个 Controller ,而不是假设我想使用我的 controllerContext(或者甚至可能为我想要的 Controller (字符串)模拟一个 controllerContext..
最佳答案
这是我的做法:
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;
}
}
和CloneControllerContext
是:
private ControllerContext CloneControllerContext()
{
ControllerContext context = new ControllerContext(Request.RequestContext, this);
return context;
}
关于c# - 将 MVC View 路由值映射到物理路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11604806/