使用 MVC 4 / Razor 在代码中加载 ASP.NET 部分视图

本文关键字:ASP 加载 NET 视图 代码 MVC Razor 使用 | 更新日期: 2023-09-27 18:34:35

>我有一个要求,我正在构建一个 HtmlHelper 扩展,它将呈现代码文章:

class Article
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string ViewName { get; set; }
}

到目前为止,我可以让它正确呈现标题和描述,但是如何将 HTML 从视图加载到我的帮助程序中并呈现它呢?

帮助程序工作原理示例:

public static Article(this HtmlHelper helper, Article article)
{
    return $"<h1>{article.Title}</h1>";
    //...need to load/append View HTML as well before returning
}

使用 MVC 4 / Razor 在代码中加载 ASP.NET 部分视图

我自己找到了答案;为了帮助他人:

public static MvcHtmlString Article(this HtmlHelper helper, Article article)
{
    StringBuilder sb = new StringBuilder();
    sb.Append($"<h1>{article.Title}</h1>");
    sb.Append(helper.Partial(article.ViewName).ToHtmlString());
    return new MvcHtmlString(sb.ToString());
}