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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
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.
1

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?

1 Comment

I am rendering jquery treeview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.