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)
You can use the Content method with the Content-Type text/html to return the HTML directly, without the need of Html. Raw . You can pass whatever Content-Type you want, such text/xml .
When you set Action's return type ActionResult , you can return any subtype of it e.g Json,PartialView,View,RedirectToAction.
To return a view from the controller action method, we can use View() method by passing respective parameters. return View(“ViewName”) – returns the view name specified in the current view folder (view extension name “. cshtml” is not required. return View("~/Views/Account/Register.
Raw allows you to output text containing html elements to the client, and have them still be rendered as such. Should be used with caution, as it exposes you to cross site scripting vulnerabilities.
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.
Simply create a property in your view model of type MvcHtmlString. You won't need to Html.Raw it then either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With