user584018
user584018

Reputation: 11344

how to change "IHtmlString" to "MvcHtmlString"?

Currently I'm writing 2 helper method to extend a implementation where I'm using "IHtmlString", how I can convert this to one method by using "MvcHtmlString"? Help...

public static IHtmlString ExceptionValidationSummary(this HtmlHelper helper)
    {
        const string template = "<div class=\"ui-widget\"><div class=\"ui-state-error ui-corner-all\" style=\"padding:0 .7em\"><div>" +
                                "<span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: .3em;\"></span>" +
                                "<strong>Validation Exceptions:</strong></div><div style=\"margin-top: 5px;\"> " + 
                                "<ul style=\"font-weight: normal;\">{0}</ul></div></div></div>";

        StringBuilder exceptionList = new StringBuilder();

        // Iterate through the exceptions
        foreach (var error in helper.ViewData.ModelState.SelectMany(modelState => modelState.Value.Errors))
        {
            exceptionList.Append(string.Format("<li>{0}</li>", error.ErrorMessage));
        }

        return exceptionList.Length.Equals(0) ? string.Format("").Raw() : string.Format(template, exceptionList).Raw();

    }

    public static IHtmlString Raw(this string value)
    {
        return new HtmlString(value);
    }

Upvotes: 1

Views: 3664

Answers (1)

Zarepheth
Zarepheth

Reputation: 2593

Though I'd expect the StringBuilder.ToString() method to be implicitly called by string.Format(), if that is not happening, explicitly call the ToString() method like this:

string.Format(template, exceptionList.ToString())

Also, your method is declared to return an IHtmlString. If you change the signature to use MvcHtmlString, that will tell the compiler your desired return type. At this point, it is just a matter of ensuring the return value matches the updated declaration:

return MvcHtmlString.Create(string.Format(template, exceptionList.ToString()));

Upvotes: 1

Related Questions