views:

49

answers:

2

What is the best way to get HTML programmatically in the view from the controller. I sometimes use string builder for that to render some html and send it the view from the controller.is it efficient?

What do you people suggests?

+1  A: 

There is nothing wrong with assembling HTML using a StringBuilder and rendering it in a view, as long as you correctly escape it.

However, it's poor design.
The controller should be ignorant of the presentation; all of the HTML should be in the view(s).
What are you trying to do?

SLaks
I am rendering jquery treeview
mazhar kaunain baig
+2  A: 

HtmlHelpers are meant for that. A better option is to create an HtmlHelper that will generate the tag you you need and all you do is pass an object to it (from the Model or ViewData in the view) and it outputs the proper tag for you. There is a TagBuilder object that will streamline everything you need.

public static string MyHtmlHelper(this HtmlHelper html, string url)
{
       TagBuilder tag = new TagBuilder("a");
       tag.Attributes.Add("href", url);
       return tag.ToString();
}

Then in your view:

<%= Html.MyHtmlHelper(ViewData["MyUrl"].ToString()) %>

This is just a quick example, you can extrapolate it to your liking.

Search asp.net mvc html helpers to understand how this works and how extension methods work.

Baddie
ok i want to generate a jquery treeview which will have a series of ul and li , you would use the same approach now also?
mazhar kaunain baig
Yes I would. You'll definitely as you'll most likely need loops and I would prefer to have the loops in a .cs files than a .aspx/.ascx file.
Baddie
You could use a partial view (.ascx) that takes a model that will represent your treeview, but I would need to know the exact details of the scenario to decide properly.
Baddie