简体   繁体   English

从参数渲染ASP.NET Core Razor标记

[英]Render ASP.NET Core Razor markup from an argument

Before ASP.NET Core, I could pass Razor markup as an argument to some function. 在ASP.NET Core之前,我可以将Razor标记作为参数传递给某些函数。 However, it doesn't seem to work anymore. 但是,它似乎不再起作用。

For example, even these simple cases render nothing: 例如,即使是这些简单的情况也无法提供任何帮助:

@{
  Func<object, HelperResult> markup1 = @<text>hello world</text>;
  new HtmlString(markup1.Invoke(null).ToString());

  Func<object, HelperResult> markup2 = @<h1>hello world</h1>;
  new HtmlString(markup2.Invoke(null).ToString());
}

What am I doing wrong? 我究竟做错了什么?

This wont render any result as you are not doing anything with the result. 这不会呈现任何结果,因为您对结果不做任何事情。

@{
  Func<object, HelperResult> markup = @<text>hello world</text>;
  new HtmlString(markup.Invoke(null).ToString());
}

In the expression new HtmlString(markup.Invoke(null).ToString()); 在表达式new HtmlString(markup.Invoke(null).ToString()); returns a HTML Result which is correct however the way you are calling it will not work correctly. 返回正确的HTML结果,但是您调用它的方式将无法正常工作。 Here is a snippet that will print the result. 这是一个将打印结果的代码段。

@{

    Func<object, HelperResult> markup = @<text>hello world</text>;
    var html = markup.Invoke(null);
    await html.WriteAction(ViewContext.Writer);
}

You will notice here we explicitly tell the html variable ( HtmlResult ) where to write to. 您会在这里注意到我们明确告诉html变量( HtmlResult )写入位置。 In this instance you will want to write to the ViewContext.Writer which is a System.IO.TextWriter . 在这种情况下,您将要写入ViewContext.Writer ,它是System.IO.TextWriter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM