Reputation: 341
Its a .Net Core 2.0 application running on Visual Studio 2017 I want to display an HTML string returned on the View.
I have added the Microsoft.AspNetCore.Html.Abstractions Nuget to my application, and I want to display an HTML sting on the Razor view, this is how my CSHTML looks like
@model EDMTLC.Models.QuickResultViewModel
@using Microsoft.AspNetCore.Html;
<div>@Html.Display(Model.ResultHTML) </div>
<div>TEST</div>
I don't think @Html.Display is the way I should be doing. In previous version .Net I used to to
<div>
<text> @MvcHtmlString.Create(Model.ReportHTML)</text>
</div>
but this will not work anymore with Core 2.0
Can someone help with an example? I found this thread, but it didn't help!
Thanks
Upvotes: 9
Views: 16024
Reputation: 1272
A more elegant solution is to build an extension method:
using Microsoft.AspNetCore.Html;
public static class StringExtensions
{
/// <summary>
/// Convert a standard string into a htmlstring for rendering in a view
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static HtmlString ToHtmlString(this string value)
{
return new HtmlString(value);
}
}
In your _ViewImports file, include the namespace if required:
@using MyProject.Extensions
Now in your views you will be able to do:
<div>@Model.ReportHTML.ToHtmlString()</div>
I'd advise doing additional sanitization in a real world app but this should answer the OP's question.
Upvotes: 8
Reputation: 339
The general rule is to avoid Html.Raw
for security reasons amongst others, better to use
Microsoft.AspNetCore.Html.HtmlContentBuilder
like so
Microsoft.AspNetCore.Html.HtmlContentBuilder DatabaseList = new Microsoft.AspNetCore.Html.HtmlContentBuilder();
DatabaseList.AppendHtml("The list of databases on this server is: " + "<br />");
foreach (var db in dbList) {
DatabaseList.AppendHtml(db.ToString() + "<br />");
}
Upvotes: 1
Reputation: 21506
Have you tried @Html.Raw()
? It should display the value as raw string, without encoding.
<pre>
<code>@Html.Raw(Model.ReportHTML)</code>
</pre>
This should work in Asp.Net Core Mvc 2.0
and previous versions as well, without the need of installing additional NuGet packages.
In order to use @Html.Display()
, if you're passing a string expression into the argument, that argument has to match one of your properties defined in your view model.
// This doesn't work
@Html.Display(Model.ResultHTML)
// This works but it encodes your HTML
@Html.Display("ResultHtml")
Or you can use @Html.DisplayFor()
and pass a lamba expression to avoid magic strings in your View
// This works but it encodes your HTML
@Html.DisplayFor(x => x.ResultHTML)
Upvotes: 3