How to return non escaped HTML content from a ViewComponent

In ASP.Net Core, ViewComponents can be used both with an actual cshtml View or by returning string data as plain text or HTML. By default, if you return 'Content' the HTML will be encoded and display the syntax of the HTML and not the rendering of it. In order to return the actual HTML so the browser renders it use the 'HtmlContentViewComponentResult' (you may want to do this if you're ajaxing in ViewComponents that contruct HTML blurbs of anything, ensure of course it's safe on your side).


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;

namespace MySite.ViewComponents

    [ViewComponent(Name = "TestViewComponent")]
    public class TestViewComponent : ViewComponent
        public TestViewComponent()


        public IViewComponentResult Invoke()
            return new HtmlContentViewComponentResult(new HtmlString("hello - <b>Yes, Hello</b>"));


I'm sharing because there weren't a lot of resources out there currently that relayed this.

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.