添加 HTML Helper 方法
打开之前创建的 MyWebApp,在项目根目录创建 Extensions 文件夹,然后在文件夹中创建 CustomHtmlHelper.cs:
using Microsoft.AspNetCore.Html;namespace Microsoft.AspNetCore.Mvc.Rendering{public static class MyHtmlHelperExtensions{public static IHtmlContent ColorfulHeading(this IHtmlHelper htmlHelper, int level, string color, string content){level = level < 1 ? 1 : level;level = level > 6 ? 6 : level;var tagName = $"h{level}";var tagBuilder = new TagBuilder(tagName);tagBuilder.Attributes.Add("style", $"color:{color ?? "green"}");tagBuilder.InnerHtml.Append(content ?? string.Empty);return tagBuilder;}}}
注意该扩展方法是声明在 Microsoft.AspNetCore.Mvc.Rendering 命名空间中的,视图会自动引用该命名空间。如果你使用自己的命名空间,记得在视图中使用 @using 手动引用。
使用 HTML Helper
在 Controllers 文件夹下创建 HomeController:
using Microsoft.AspNetCore.Mvc;namespace MyWebApp{public class HomeController : Controller{public IActionResult Index(){ViewData["country"] = "United States";ViewData["state"] = "Washington";ViewData["county"] = "King";ViewData["city"] = "Redmond";return View();}}}
添加 Index 视图,使用 HTML Helper:
<html><body>@Html.ColorfulHeading(1, "red", ViewData["country"].ToString())@Html.ColorfulHeading(2, "orange", ViewData["state"].ToString())@Html.ColorfulHeading(3, "blue", ViewData["county"].ToString())@Html.ColorfulHeading(4, "greem", ViewData["city"].ToString())</body></html>
