我如何能有一个视图呈现部分(用户控件)从不同的文件夹? 有了预览3,我习惯用完整的路径调用RenderUserControl,但升级到预览5,这是不可能的了。 相反,我们得到了RenderPartial方法,但它没有提供我所寻找的功能。
当前回答
创建一个自定义视图引擎,并有一个返回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
其他回答
在我的情况下,我正在使用MvcMailer (https://github.com/smsohan/MvcMailer),并想从另一个文件夹访问部分视图,这不在“共享”中。上面的解决方案不起作用,但是使用相对路径可以。
@Html.Partial("../MyViewFolder/Partials/_PartialView", Model.MyObject)
只需要包含视图的路径和文件扩展名。
剃须刀:
@Html.Partial("~/Views/AnotherFolder/Messages.cshtml", ViewData.Model.Successes)
ASP。NET引擎:
<% Html.RenderPartial("~/Views/AnotherFolder/Messages.ascx", ViewData.Model.Successes); %>
如果这不是你的问题,你能包括你的代码,用来与RenderUserControl工作吗?
VirtualPathProviderViewEngine是WebFormsViewEngine的基础,它应该支持路径前面的“~”和“/”字符,所以上面的例子应该可以工作。
我注意到你的例子使用了路径“~/Account/myPartial”。ascx”,但是您提到您的用户控件在Views/Account文件夹中。你试过了吗
< %。RenderPartial(“~点击量/ Html / myPartial . ascx”);% >账户
还是你的问题打错了?
对于使用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上的信息也很有用。
尝试使用RenderAction("myPartial","Account");
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制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?