我目前正在尝试将 ASP.net MVC 5 项目迁移到 MVC 6。
我将如何迁移以下代码:
public static class SectionExtensions
{
public static HelperResult RenderSection(this WebPageBase webPage, [RazorSection] string name, Func<dynamic, HelperResult> defaultContents)
{
return webPage.IsSectionDefined(name) ? webPage.RenderSection(name) : defaultContents(null);
}
}
[RazorSection] 是 JetBrains.Annotations 程序集的一部分。
最佳答案
而不是 WebPageBase
我用了RazorPage
在 Microsoft.AspNet.Mvc.Razor
namespace Stackoverflow
{
public static class SectionExtensions
{
public static IHtmlContent RenderSection(this RazorPage page, [RazorSection] string name, Func<dynamic, IHtmlContent> defaultContents)
{
return page.IsSectionDefined(name) ? page.RenderSection(name) : defaultContents(null);
}
}
}
然后引用 Razor 页面中的类
@using static Stackoverflow.SessionExtensions
,并这样称呼它:@this.RenderSection("extra", @<span>This is the default!</span>))
一个 替代 方法是在 View 中执行此操作(我更喜欢这种方式,似乎更简单):
@if (IsSectionDefined("extra"))
{
@RenderSection("extra", required: false)
}
else
{
<span>This is the default!</span>
}
我希望这有帮助。
更新 1 (来自评论)
通过引用命名空间
@using Stackoverflow
您不必包含
static
关键字,但是在调用它时,您必须引用命名空间中的实际类并传递 ' 这个 ' 进入函数。@SectionExtensions.RenderSection(this, "extra", @<span>This is the default!</span>)
更新 2
razor 中有一个错误,不允许您调用模板委托(delegate)
Func <dynamic, object> e = @<span>@item</span>;
一节内。请看 https://github.com/aspnet/Razor/issues/672当前的解决方法:
public static class SectionExtensions
{
public static IHtmlContent RenderSection(this RazorPage page, [RazorSection] string name, IHtmlContent defaultContents)
{
return page.IsSectionDefined(name) ? page.RenderSection(name) : defaultContents;
}
}
然后是 Razor 页面:
section test {
@this.RenderSection("extra", new HtmlString("<span>this is the default!</span>"));
}
关于view - 如何在 MVC 6 中定义具有默认内容的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34784314/