Hello guys, I've made a structure to retrieve from database, based on the role given, to return menu itens. Now, I need to make a recursive method to render this HTML in the controller and pass this HTML to view. But i just don't know how to write native HTML in the controller. Any suggestions?
The controller should not handle any of the HTML at all. That's what the view in MVC is for. Your controller should pass a data structure from the model, and the view should render that data structure as HTML.
It's definitely not the idea of MVC (or whatever you're doing) to render HTML in the Controller. HTML has to be handled in the view. What if you want to provide an alternative UI (e.g. Windows Application)? HTML does not really fit into an WinApp.
You can use an HTML helper to create the HTML. For example, we have a Menu system that is very complex, so we create an HtmlHelper extension. Here's a simple html extension (I use TagBuilders to make the HTML easier ... very handy when you have lots of nested tags).
public static String MyNewExtension(this HtmlHelper html, String extraVariable)
{
if (html == null)
{
throw new ArgumentNullException("html");
}
TagBuilder h1Tag = newTagBuilder("h1");
h1Tag.InnerHtml = extraVariable;
return h1Tag.ToString();
}
Easier than you might think:
Controller:
ViewData["html"] = @"<a href='http://www.stackoverflow.com'>Stack Overflow</a>";
View:
<%= ViewData["html"] %>
I do agree this isn't the best method. I would suggest you write the html markup in your view and substitute the values from your model instead.
e.g.
Controller:
ViewData["Title"] = "Stack Overflow";
ViewData["Url"] = @"http://www.stackoverflow.com";
View:
<a href="<%=Html.Encode( ViewData["Url"] )%>">
<%=Html.Encode( ViewData["Title"] )%></a>
If you have to create many, you could use a partial view / user control to encapsulate the common markup.