In my console application, I have a .cshtml
Razor file. In the file properties, I have set RazorTemplatePreprocessor
as the Custom Tool
meaning it is a so-called "Preprocessed Razor Template" (this was explicitly available to pick in the "New File" dialog in older VS versions). When saving the file, Visual Studio creates a C# class so that at runtime I can transform the Razor template into a string which contains the HTML.
When I have a directive like @Model.GetMyString()
in my template, the template engine generates Write(Model.GetMyString())
for the C# class code. The Write
method encodes the received string using WebUtility.HtmlEncode
. How can I make it so that a call to the WriteLiteral
method will be generated instead, as that would preserve the result of GetMyString()
as-is?
@Html.Raw
is not an option because the preprocessor / template engine doesn't know that directive.
In my console application, I have a .cshtml
Razor file. In the file properties, I have set RazorTemplatePreprocessor
as the Custom Tool
meaning it is a so-called "Preprocessed Razor Template" (this was explicitly available to pick in the "New File" dialog in older VS versions). When saving the file, Visual Studio creates a C# class so that at runtime I can transform the Razor template into a string which contains the HTML.
When I have a directive like @Model.GetMyString()
in my template, the template engine generates Write(Model.GetMyString())
for the C# class code. The Write
method encodes the received string using WebUtility.HtmlEncode
. How can I make it so that a call to the WriteLiteral
method will be generated instead, as that would preserve the result of GetMyString()
as-is?
@Html.Raw
is not an option because the preprocessor / template engine doesn't know that directive.
Turns out it's possible to just directly call the WriteLiteral
method from inside the Razor template:
@model MyNamespace.MyModel
<div>
@{
WriteLiteral(Model.GetMyString()); // At this position the return
// value of GetMyString will be appended raw (not encoded)!
}
</div>
HtmlString
? So@(new HtmlString(Model.GetMyString()))
or similar. – Jon Skeet Commented Jan 16 at 7:46System.Web.HtmlString
orMicrosoft.AspNetCore.Html.HtmlString
? I tried the latter from theMicrosoft.AspNetCore.Html.Abstractions
package, but it did not change the generated output. – user764754 Commented Jan 16 at 7:58Html.Raw
- perhaps stackoverflow.com/questions/73120769 might be useful?) If you can give enough information to make this easy to reproduce, it would make it easier to help you. – Jon Skeet Commented Jan 16 at 8:05as Action<System.IO.TextWriter>
. If the result is notnull
it will append the string without encoding. It seems likeHtmlString
doesn't fall under that. You mean I should try@(new HtmlString(Model.GetMyString()))
in a regular ASP.NET Core Razor Page? – user764754 Commented Jan 16 at 8:15