Two ways to output Html in ASP. NET Razor template engine

  • 2021-08-05 09:32:25
  • OfStack

This article illustrates two ways to output Html in the ASP. NET Razor template engine. Share it for your reference, as follows:

All Html in Razor will be encoded automatically, so we don't need to encode manually (security), but when we need to output Html, it is the escaped Html text, as follows:


@{
  string thisTest = "<span style=\"color:#f00;\">qubernet</span>";
}
@thisTest;

So the text output on the page is: < span style=\"color:#f00;\" > qubernet < /span > Instead of red fonts, there are two commonly used ways to output red fonts:

1. Use Html. Raw in Razor (this is recommended):


@{
  string thisTest = "<span style=\"color:#f00;\">qubernet</span>";
}
@Html.Raw(thisTest);

2. Use the MvcHtmlString class to implement:


@{
  string thisTest = "<span style=\"color:#f00;\">qubernet</span>";
  var thisResult = new MvcHtmlString(thisTest);
}
@thisResult Or @(new HtmlString(thisTest))

For more readers interested in asp. net related contents, please check the topics on this site: "Summary of asp Optimization Skills", "Summary of asp. net String Operation Skills", "Summary of asp. net Operation Skills of XML", "Summary of asp. net File Operation Skills", "Summary of asp. net ajax Skills" and "Summary of asp. net Cache Operation Skills".

I hope this article is helpful to everyone's asp. net programming.


Related articles: