Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building HtmlStrings in ASP.NET MVC

I have an extension method that needs to return an HtmlString. The method has a loop which will build the HtmlString, however the HtmlString object has no Append method and does not allow concatenation using the + operator so I am not sure how I would build the HtmlString.

I'd like to use the StringBuilder but it doesn't have a ToHtmlString method...

Any solutions or patterns for this?

like image 989
Judo Avatar asked Oct 26 '11 12:10

Judo


People also ask

What is MVC HTML string?

Creates an HTML-encoded string using the specified text value. Determines whether the specified string contains content or is either null or empty.

How add HTML to MVC?

Step 1: Right click on the "Controllers" folder and add "LoadHtml" controller. Copy and paste the following code. Step 2: Right click on the "Index" action method in the "LoadHtmlController" and add "Index" view.

Does MVC use HTML?

In MVC, HTML Helper can be considered as a method that returns you a string. This string can describe the specific type of detail of your requirement. Example: We can utilize the HTML Helpers to perform standard HTML tags, for example HTML<input>, and any <img> tags.

What is the difference between DisplayNameFor and DisplayFor in MVC?

DisplayFor displays the value for the model item and DisplayNameFor simply displays the name of the property?


4 Answers

Why not just build the string in a stringbuilder and then return MvcHtmlString.Create(sb.ToString());

like image 53
Tetaxa Avatar answered Oct 20 '22 18:10

Tetaxa


i think you want to use TagBuilder and see Using the TagBuilder Class to Build HTML Helpers

like below..

   // Create tag builder
            var builder = new TagBuilder("img");

            // Create valid id
            builder.GenerateId(id);

            // Add attributes
            builder.MergeAttribute("src", url);
            builder.MergeAttribute("alt", alternateText);
            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

            // Render tag
            return builder.ToString(TagRenderMode.SelfClosing);
like image 31
swapneel Avatar answered Oct 20 '22 18:10

swapneel


You could have a look at the fubu spin-off for creating HTML Tags. Here is a SO question that talks a bit about its usage.

like image 1
flq Avatar answered Oct 20 '22 20:10

flq


You could write the ToHtmlString() method yourself as a extension method on StringBuilder.

like image 1
Mattias Jakobsson Avatar answered Oct 20 '22 18:10

Mattias Jakobsson