我目前正在尝试将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 (来自评论)
通过引用 namespace
@using Stackoverflow
您不必包括
static
关键字,但是在调用它时,您必须引用 namespace 中的实际类,并将' this '传递给函数。@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>"));
}