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?
Creates an HTML-encoded string using the specified text value. Determines whether the specified string contains content or is either null or empty.
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.
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.
DisplayFor displays the value for the model item and DisplayNameFor simply displays the name of the property?
Why not just build the string in a stringbuilder and then return MvcHtmlString.Create(sb.ToString());
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);
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.
You could write the ToHtmlString()
method yourself as a extension method on StringBuilder
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With