ASP.NET MVC Razor render without encoding

后端 未结 7 2242
悲&欢浪女
悲&欢浪女 2020-11-29 02:42

Razor encodes string by default. Is there any special syntax for rendering without encoding?

7条回答
  •  感情败类
    2020-11-29 03:00

    As well as the already mentioned @Html.Raw(string) approach, if you output an MvcHtmlString it will not be encoded. This can be useful when adding your own extensions to the HtmlHelper, or when returning a value from your view model that you know may contain html.

    For example, if your view model was:

    public class SampleViewModel
    {
      public string SampleString { get; set; }
      public MvcHtmlString SampleHtmlString { get; set; }
    }
    

    For Core 1.0+ (and MVC 5+) use HtmlString

    public class SampleViewModel
    {
      public string SampleString { get; set; }
      public HtmlString SampleHtmlString { get; set; }
    }
    

    then

    
    
    @Model.SampleString
    @Html.Raw(Model.SampleString)
    @Model.SampleHtmlString

提交回复
热议问题