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

@MvcHtmlString.Create(ViewBag.HtmlOutput)

or

@(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=\"http://commons.wikimedia.org/wiki/Main_Page\">Wikimedia Commons</a>");
        htmlOutput.Append("</p>");
        htmlOutput.Append("<img src=\"http://upload.wikimedia.org/wikipedia/commons/6/63/CampNou.jpg\" alt=\"Cam Nou\" title=\"Cam Nou\"/>");
        ViewBag.HtmlOutput = htmlOutput.ToString();                
        return View();
    }
}

Which can be used in a view like this

@{
    ViewBag.Title = "Index";
}

@Html.Raw(ViewBag.HtmlOutput)

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).

Comments

  • 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!