In an ASP.NET Core app I want to return custom html from a ViewComponent. I can return custom text, but the html will be encoded instead of being embedded:
public class BannerViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(string param1, int param2)
{
return Content("<strong>some custom html</strong>");
}
}
I use it in my .cshtml page:
@await Component.InvokeAsync("BannerView")
On the page this will Show as <strong>some custom html</strong>
instead of some custom html.
How do I directly return HTML instead of text from the ViewComponent?
Your ViewComponent could have its own view as well and you can render the html there. The solution would be the following:
public class BannerViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(string param1, int param2)
{
string model = "<strong>some custom html</strong>";
return View("Index", model);
}
}
Add the following to your Views folder: Views\Shared\Components\BannerViewComponent\Index.cshtml
and put the following in the ViewComponent's view:
@model string
@Html.Raw(Model)
You can change the model to be a class instead of just a string so that you can structure the ViewComponent's output, but the key part is the Html.Raw()
method to output unencoded html.