Html.Raw (转)

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

posted @ 2014-04-16 09:33  邹邹  Views(390)  Comments(0)    收藏  举报