Search code examples
c#asp.net-mvc-3controllerreturn

asp.net mvc3: How to return raw html to view?


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)

Solution

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