Building HtmlStrings in ASP.NET MVC

13.4k views Asked by At

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?

5

There are 5 answers

0
swapneel On BEST ANSWER

I think you want to use TagBuilder. See also Using the TagBuilder Class to Build HTML Helpers like this:

// 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);
0
Judo On

There are several solutions to this including using the TagBuilder, but using Html.Raw() worked very well for me:

public static IHtmlString HtmlMethod(this HtmlHelper htmlhelper, Object object)
{
    var sb = new StringBuilder();
    foreach (var item in object)
    {
        sb.Append(object.outputStr)
    }
    return htmlHelper.Raw(sb.ToString());
}
0
Tetaxa On

Why not just build the string in a stringbuilder and then

return MvcHtmlString.Create(sb.ToString());
0
flq On

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.

0
Mattias Jakobsson On

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