如何让MVC在嵌套文件夹中查找视图

edi*_*ode 9 c# razor asp.net-mvc-3

我对MVC和Razor的了解非常基础,所以我希望它的内容相当简单.基本上,我有我的Controllers正常,但我的Views文件夹有一个嵌套的结构.例如,而不是:

Views -> Index.cshtml
Run Code Online (Sandbox Code Playgroud)

它像是

Views -> BrandName -> Index.cshtml
Run Code Online (Sandbox Code Playgroud)

我创建了一个自定义助手来解决这个问题,但我不确定它如何与查询字符串网址一起使用?这里有一个控制器:

    private DataService ds = new DataService();

    //
    // GET: /Collections/

    public ActionResult Index()
    {
        return View();
    }


    //
    // GET: /Collections/Collection?id=1
    public ActionResult Collection(int id)
    {
        var collectionModel = ds.GetCollection(id);
        return View(collectionModel);
    }
Run Code Online (Sandbox Code Playgroud)

但是我该如何ActionResult Collection看待:

Views -> Brand2 -> Collection.cshtml
Run Code Online (Sandbox Code Playgroud)

这是我使用的解决方法:

public static string ResolvePath(string pageName)
    {
        string path = String.Empty;
        //AppSetting Key=Brand
        string brand = ConfigurationManager.AppSettings["Brand"];

        if (String.IsNullOrWhiteSpace(brand))
            path = "~/Views/Shared/Error.cshtml"; //Key [Brand] was not specified
        else
            path = String.Format("~/Views/{0}/{1}", brand, pageName);

        return path;
    }
Run Code Online (Sandbox Code Playgroud)

hea*_*150 12

使用以下内容

public ActionResult Collection(int id)
{
    var collectionModel = ds.GetCollection(id);
    return View("/Brand2/Collection", collectionModel);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将搜索以下视图.

~/Views/Brand2/Collection.aspx
~/Views/Brand2/Collection.ascx
~/Views/Shared/Brand2/Collection.aspx
~/Views/Shared/Brand2/Collection.ascx
~/Views/Brand2/Collection.cshtml
~/Views/Brand2/Collection.vbhtml
~/Views/Shared/Brand2/Collection.cshtml
~/Views/Shared/Brand2/Collection.vbhtml
Run Code Online (Sandbox Code Playgroud)

或者更直接

public ActionResult Collection(int id)
    {
        var collectionModel = ds.GetCollection(id);
        return View("~/Brand2/Collection.cshtml", collectionModel);
    }
Run Code Online (Sandbox Code Playgroud)

现在,我想第一个警告你,你永远不应该,永远不要使用这个答案.遵循MVC应用程序中固有的约定是有充分理由的.将文件放在已知位置可以让每个人更容易理解您的应用程序.