Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc3 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) 
like image 370
River Avatar asked Oct 07 '11 00:10

River


People also ask

How do I return an HTML controller?

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 .

Can I return action result instead of view result?

When you set Action's return type ActionResult , you can return any subtype of it e.g Json,PartialView,View,RedirectToAction.

How do I return a view from the action method?

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.

What does HTML raw do C#?

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.


2 Answers

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.

like image 137
archil Avatar answered Nov 24 '22 14:11

archil


Simply create a property in your view model of type MvcHtmlString. You won't need to Html.Raw it then either.

like image 41
Adam Tuliper Avatar answered Nov 24 '22 15:11

Adam Tuliper