gpt4 book ai didi

asp.net-mvc - Asp.Net MVC 更改 DisplayModeProvider 的 View 位置

转载 作者:行者123 更新时间:2023-12-01 11:36:35 25 4
gpt4 key购买 nike

我开发了具有大量 View 的大型 Web 应用程序。将桌面/移动 View 保存在同一个文件夹中很麻烦。是否可以将移动 View (name.Mobile.cshtml) 分组到显式子文件夹中并告诉 DisplayModeProvider 在那里查找 View ?例如,

Views/Home/Index.Mobile.cshtml 移动到 Views/Home/Mobile/Index.Mobile.cshtmlViews/People/List.Mobile.cshtml 移动到 Views/People/Mobile/List.Mobile.cshtml

最佳答案

好吧,我找到了一些解决这个问题的方法。

  1. 我可以实现自定义 RazorViewEngine(WebFormViewEngine) 并指定我自己的 ViewLocationFormats 集合。

  2. 我可以使用区域来实现此行为。

  3. 我可以实现自定义 DefaultDisplayMode 并覆盖 TransformPath() 方法来更改 View 位置。

我认为第三种方式更容易和简单。这是代码:

首先我创建自定义 DisplayMode 并从 DefaultDisplayMode 继承它:

public class NewDisplayMode : DefaultDisplayMode
{
public NewDisplayMode()
: base("Mobile") //any folder name you like, or you can pass it through parameter
{

}

public NewDisplayMode(string folderName)
: base(folderName) //any folder name you like, or you can pass it through parameter
{

}

protected override string TransformPath(string virtualPath, string suffix)
{
string view = Path.GetFileName(virtualPath);
string pathToView = Path.GetDirectoryName(virtualPath);
virtualPath = (pathToView + "\\" + suffix + "\\" + view).Replace("\\", "/");

return virtualPath;
}
}

在上面的代码中,我覆盖了 TransformPath() 方法并转换 virtualPath 字符串以将位置更改为 View 。

接下来我需要的是将此模式添加到模式集合中:

protected void Application_Start()
{
DisplayModeProvider.Instance.Modes.RemoveAt(0);
DisplayModeProvider.Instance.Modes.Insert(0, new NewDisplayMode()
{
ContextCondition = context => context.GetOverriddenBrowser().IsMobileDevice
//ContextCondition = context => context.Request.Url.Host == "www.m.mysite.com"
});
//other code
}

因此,我不需要重命名我的 View 文件,我对移动和桌面 View 使用相同的名称。最后,我的文件夹结构如下所示:

enter image description here

关于asp.net-mvc - Asp.Net MVC 更改 DisplayModeProvider 的 View 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26488321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com