【问题标题】:asp.net core render a view into stringwriterasp.net core 将视图呈现到 stringwriter
【发布时间】:2018-03-30 08:20:02
【问题描述】:

所以我想构建一个 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。

【问题讨论】:

标签: asp.net-core


【解决方案1】:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    相关资源
    最近更新 更多