asp.net核心将视图渲染为字符串编写器

时间:2018-03-29 23:16:52

标签: asp.net-core

所以我想构建一个Html自定义构建器,它将模型对象传递给局部视图并将页面呈现为StringWriter

        public static class HtmlExtensions
        {
            public static HtmlString BuildTextboxFor(this IHtmlHelper helper, object model)
            {
            //Find the partial view and pass the Model through it.

            //Render the page into a StringWriter

            //return new HtmlString(StringWriter object);
            }
        }

模型名称将是部分名称。我似乎无法找到.NET CORE的解决方案。所有资源似乎都适用于ASP.NET Framework。

1 个答案:

答案 0 :(得分:0)

IHtmlHelper.Partial返回IHtmlContentHtmlString只是同一抽象的另一个实现。查看示例代码,这是所需的结果(不是StringWriter

public static HtmlString BuildTextboxFor(this IHtmlHelper helper, object model) {
    return helper.Partial($"~/Views/{model.GetType().Name}.cshtml", model)
}

如果您仍想将视图写入StringWriter这不是问题:

var content = helper.Partial($"~/Views/{model.GetType().Name}.cshtml", model);
using(var writer = new StringWriter()) {
    content.WriteTo(writer, HtmlEncoder.Default);
}