asp.net mvc3 return raw html to view

River picture River · Oct 7, 2011 · Viewed 100.8k times · Source

Are there other ways I can return raw html from controller? As opposed to just using viewbag. like below:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.HtmlOutput = "<HTML></HTML>";
        return View();
    }
}

@{
    ViewBag.Title = "Index";
}

@Html.Raw(ViewBag.HtmlOutput)

Answer

archil picture archil · Oct 7, 2011

There's no much point in doing that, because View should be generating html, not the controller. But anyways, you could use Controller.Content method, which gives you ability to specify result html, also content-type and encoding

public ActionResult Index()
{
    return Content("<html></html>");
}

Or you could use the trick built in asp.net-mvc framework - make the action return string directly. It will deliver string contents into users's browser.

public string Index()
{
    return "<html></html>";
}

In fact, for any action result other than ActionResult, framework tries to serialize it into string and write to response.