Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return html string from controller and display in view

How can I return a model with a string propertie containing <li> elements and display it in view? If I just write @Model.Messages it shows all the string.. i need it in html format.

like image 954
MuriloKunze Avatar asked May 19 '12 01:05

MuriloKunze


People also ask

How do you return a string in HTML?

Use ControllerBase. The first string represents the content of the HTML while the last is the content-type which for HTML is "text/html" . Since our controller derives from ControllerBase , we simply call base. Content() and pass the required parameter to return the desired HTML.

What are methods that return an HTML string in ASP NET MVC called?

HtmlEncode() to send html to view and then use the Server. HtmlDecode() to get the html to display on the view. Then you can use @Html.

Does the controller return a view?

A controller action might return a view. However, a controller action might perform some other type of action such as redirecting you to another controller action.

Is it possible to pass a model object to a view from a controller?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.


2 Answers

You can use the Content method with the Content-Type text/html to return the HTML directly, without the need of Html.Raw.

public ActionResult MyHtmlView() {
    return Content("<html><body>Ahoy.</body></html>", "text/html")
}

You can pass whatever Content-Type you want, such text/xml.

like image 71
Kim Tranjan Avatar answered Oct 02 '22 20:10

Kim Tranjan


You don't say which rendering engine you're using:

MVC3:
@Html.Raw(Model.Description)

like image 30
web_bod Avatar answered Oct 02 '22 18:10

web_bod