Using Html.Raw in ASP.NET MVC Razor Views

With the release of ASP.NET MVC 3 Release Candidate 2 (RC2) you can finally use Html.Raw when you don’t your output to be encoded.

So this means you don’t have to use



@(new HtmlString(ViewBag.HtmlOutput))

or anything else to output a string containing HTML in ASP.NET MVC.

An example of using Html.Raw in ASP.NET MVC 3 using Razor

The code below shows the HTML string to be outputted being added the dynamic ViewBag collection.

public class HomeController : Controller
    public ActionResult Index()
        StringBuilder htmlOutput = new StringBuilder();
        htmlOutput.Append("<p>The image below is from " );
        htmlOutput.Append("<a href=\"\">Wikimedia Commons</a>");
        htmlOutput.Append("<img src=\"\" alt=\"Cam Nou\" title=\"Cam Nou\"/>");
        ViewBag.HtmlOutput = htmlOutput.ToString();                
        return View();

Which can be used in a view like this

    ViewBag.Title = "Index";


to show the following output in a browser

Output Using HtmlRaw in ASP.NET MVC

For more information check out Scott Gu’s post Announcing ASP.NET MVC 3 (Release Candidate 2).


  • Stuart Gardner-Vaughan

    Although I’m sure the example was just illustrative, I’d recommend against having HTML directly in your compiled controller class.  Kind of defeating the beauty of MVC!