在ASP.NET Core MVC应用程序中,创建一个名为 CustomHtmlHelper 的类。在该类中,定义一个名为MyCustomSection的静态字符串,用于在自定义HtmlHelper中添加视图部分。
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
public static class CustomHtmlHelper
{
public static string MyCustomSection = "MyCustomSection";
public static IHtmlContent CustomSection(this IHtmlHelper htmlHelper, string content)
{
htmlHelper.ViewContext.HttpContext.Items[MyCustomSection] += content;
return null;
}
}
在视图中使用自定义HtmlHelper。 使用@using导入CustomHtmlHelper类。 然后使用自定义HtmlHelper的CustomSection方法添加视图部分。
@using CustomHtmlHelper
This is a custom section:
@Html.CustomSection("Some content for my custom section!")
在Layout视图中,添加以下代码访问CustomHtmlHelper的MyCustomSection视图部分。这将在Layout视图中显示视图部分内容。
@using CustomHtmlHelper
@Html.Raw(Context.Items[CustomHtmlHelper.MyCustomSection])