开发者

asp.net mvc getting html programmatically in view

What is the best way to get HTML programmatically in the view from the controller. I sometimes开发者_JAVA百科 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?


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜