0

So far it is working, but I can't seem to nail down the HTML in the correct order needed.

For every different error I need this HTML returned:

<div class="style-msg errormsg">
    <div class="sb-msg">
        <i class="icon-remove"></i>
        Error Text
    </div>
</div>

Here is the extension method:

public static string MyValidationSummary(this HtmlHelper helper, string validationMessage = "")
        {
            string retVal = "";
            if (helper.ViewData.ModelState.IsValid)
                return "";
            retVal += "<div class='style-msg errormsg'><div class='sb-msg'><i class='icon-remove'></i>";
            if (!String.IsNullOrEmpty(validationMessage))
                retVal += helper.Encode(validationMessage);
            foreach (var key in helper.ViewData.ModelState.Keys)
            {
                foreach (var err in helper.ViewData.ModelState[key].Errors)
                    retVal += helper.Encode(err.ErrorMessage);
            }
            retVal += "</div></div>";
            return retVal.ToString();
        }
    }

And finally here is how I call it on the actual webpage.

@Html.Raw(Html.MyValidationSummary())

BONUS Q: Is using HTML.Raw safe in this instance?

James Wilson
  • 5,074
  • 16
  • 63
  • 122

1 Answers1

0

After playing around with it a bit I came to this conclusion. I changed the HTML a bit because I wanted to use the Bootstrap alert boxes.

public static string MyValidationSummary(this HtmlHelper helper, string validationMessage = "")
{
    string retVal = "";
    string errorList = "";

    foreach (var key in helper.ViewData.ModelState.Keys)
    {
        retVal = "";

        foreach (var err in helper.ViewData.ModelState[key].Errors)
        {
            retVal += "<div class='alert alert-danger'>";
            retVal += "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>";
            retVal += "<i class='icon-remove-sign'></i>";
            retVal += helper.Encode(err.ErrorMessage);
            retVal += "</div>";
            errorList += retVal;
        }


    }

    return errorList.ToString();
}
James Wilson
  • 5,074
  • 16
  • 63
  • 122