我如何能有一个视图呈现部分(用户控件)从不同的文件夹? 有了预览3,我习惯用完整的路径调用RenderUserControl,但升级到预览5,这是不可能的了。 相反,我们得到了RenderPartial方法,但它没有提供我所寻找的功能。
当前回答
你应该试试这个
~/Views/Shared/parts/UMFview.ascx
将~/Views/放在代码之前
其他回答
如果你经常使用其他路径,你可以永久地修复它,而不需要一直指定路径。默认情况下,它会检查“视图”文件夹和“共享”文件夹中的部分视图。但如果你想加一个。
在Models文件夹中添加一个类:
public class NewViewEngine : RazorViewEngine {
private static readonly string[] NEW_PARTIAL_VIEW_FORMATS = new[] {
"~/Views/Foo/{0}.cshtml",
"~/Views/Shared/Bar/{0}.cshtml"
};
public NewViewEngine() {
// Keep existing locations in sync
base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NEW_PARTIAL_VIEW_FORMATS).ToArray();
}
}
然后在Global.asax.cs文件中添加以下一行:
ViewEngines.Engines.Add(new NewViewEngine());
你应该试试这个
~/Views/Shared/parts/UMFview.ascx
将~/Views/放在代码之前
创建一个自定义视图引擎,并有一个返回ViewEngineResult的方法 在本例中,您只需覆盖_options。ViewLocationFormats和添加您的文件夹目录 :
public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage)
{
var controllerName = context.GetNormalizedRouteValue(CONTROLLER_KEY);
var areaName = context.GetNormalizedRouteValue(AREA_KEY);
var checkedLocations = new List<string>();
foreach (var location in _options.ViewLocationFormats)
{
var view = string.Format(location, viewName, controllerName);
if (File.Exists(view))
{
return ViewEngineResult.Found("Default", new View(view, _ViewRendering));
}
checkedLocations.Add(view);
}
return ViewEngineResult.NotFound(viewName, checkedLocations);
}
例如:https://github.com/AspNetMonsters/pugzor
对于使用ASP的读者。NET Core 2.1或更高版本,想要使用Partial Tag Helper语法,试试这个:
<partial name="~/Views/Folder/_PartialName.cshtml" />
波浪号(~)是可选的。
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-3.1#partial-tag-helper上的信息也很有用。
对于名为myPartial的用户控件。ascx位于Views/Account文件夹,如下所示:
<%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- ASP中基于角色的访问控制(RBAC)与基于声明的访问控制(CBAC)NET MVC
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- 带有空模型的Renderpartial传递了错误的类型
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- MVC4数据类型。日期编辑器不会在Chrome中显示日期值,在Internet Explorer中没问题
- 如何将此foreach代码转换为Parallel.ForEach?