我对 MVC 和 Razor 的了解非常基础,所以我希望它的知识相当简单。基本上,我的 Controllers
和往常一样,但我的 Views
文件夹具有嵌套结构。例如,而不是:
Views -> Index.cshtml
好像是
Views -> BrandName -> Index.cshtml
我创建了一个自定义助手来解决这个问题,但我不确定它如何与查询字符串 url 一起工作?作为一个例子,这里有一个 Controller :
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);
}
但是我如何获取 ActionResult Collection
来查看:
Views -> Brand2 -> Collection.cshtml
这是我使用的解决方法:
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;
}
最佳答案
使用以下内容
public ActionResult Collection(int id)
{
var collectionModel = ds.GetCollection(id);
return View("/Brand2/Collection", collectionModel);
}
以上代码将搜索以下 View 。
~/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
或者更直接
public ActionResult Collection(int id)
{
var collectionModel = ds.GetCollection(id);
return View("~/Brand2/Collection.cshtml", collectionModel);
}
现在,我想成为第一个警告您的人,您永远、永远、永远不要使用这个答案。遵循 MVC 应用程序中固有的约定是有充分理由的。将您的文件放在已知位置可以让每个人更容易理解您的应用程序。
关于c# - 如何让 MVC 到嵌套文件夹中的查找 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9582357/