c# - 将 MVC View 路由值映射到物理路径

标签 c# asp.net-mvc-3 routes asp.net-mvc-routing

假设我有一个具有 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/

相关文章:

c# - UWP - 无法读取串行端口 COM

c# - Linq:合并字典

asp.net-mvc-3 - EditorTemplate 的嵌套模型的 ASP.NET MVC3 条件验证

asp.net-mvc - url 中的 ASP.NET MVC2 垃圾

c# - 在 C# 中读取数组列

c# - 如何在 buttton 的 onClick 事件中使用 asp.net 下载文件?

c# - ASP.NET MVC 4 C# HttpPostedFileBase,如何存储文件

c# - 格式化逻辑属于 MVC 的什么地方?

php - CakePHP动态路由配置,可能吗?或者只是一个梦想?

javascript - JS工兵: posting data to server (the right way ?)