我如何能有一个视图呈现部分(用户控件)从不同的文件夹? 有了预览3,我习惯用完整的路径调用RenderUserControl,但升级到预览5,这是不可能的了。 相反,我们得到了RenderPartial方法,但它没有提供我所寻找的功能。
当前回答
VirtualPathProviderViewEngine是WebFormsViewEngine的基础,它应该支持路径前面的“~”和“/”字符,所以上面的例子应该可以工作。
我注意到你的例子使用了路径“~/Account/myPartial”。ascx”,但是您提到您的用户控件在Views/Account文件夹中。你试过了吗
< %。RenderPartial(“~点击量/ Html / myPartial . ascx”);% >账户
还是你的问题打错了?
其他回答
对于名为myPartial的用户控件。ascx位于Views/Account文件夹,如下所示:
<%Html.RenderPartial("~/Views/Account/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上的信息也很有用。
如果你经常使用其他路径,你可以永久地修复它,而不需要一直指定路径。默认情况下,它会检查“视图”文件夹和“共享”文件夹中的部分视图。但如果你想加一个。
在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());
在我的情况下,我正在使用MvcMailer (https://github.com/smsohan/MvcMailer),并想从另一个文件夹访问部分视图,这不在“共享”中。上面的解决方案不起作用,但是使用相对路径可以。
@Html.Partial("../MyViewFolder/Partials/_PartialView", Model.MyObject)
创建一个自定义视图引擎,并有一个返回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
推荐文章
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架
- 在什么情况下SqlConnection会自动被征召到环境事务范围事务中?
- 用c#解析JSON
- Windows窗体中的标签的换行
- 为什么在c#中使用finally ?
- 为什么我不能在c#中有抽象静态方法?
- ASP是什么?NET Identity的IUserSecurityStampStore<TUser>接口?
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?