简体   繁体   中英

How do I get HTML or New Line / Carraige Return in Html.ValidationSummary() via C#?

This may not be possible without writing some crazy extension method which I do not plan on doing. I know the ValidationSummary() is encoded for security. I'm just curious if I'm missing something obvious...?

I have a simple <%= Html.ValidationSummary() %> in my form. For certain situations, errors are thrown and it would be nice if I could have a little more control over the appearance of the error(s).

For example - when I import a CSV file, I throw the following error to the ValidationSummary() if the headers are not in an acceptable format or include special characters:

constraintValidatorContext.AddInvalid(invalidHeaders.Count() == 1
                        ? string.Format("The following column header is invalid: {0}.", badHeaders)
                        : string.Format("There were multiple invalid column headers including: {0}.", badHeaders), "General");

It would be swell if I could display the multiple headers in a list as follows :

string.Format("There were multiple invalid column headers including: <li>{0}</li>", badHeaders)

This displays the HTML. Even if I could just throw in a NewLine here or there, it would be helpful (\\n \\r) ... Am I just ignorant of something?

Newlines have no effect in HTML, you want a <br /> tag.

You could always roll your own to get more control over the output. Here's the MVC2 source for that helper. It basically looks through the

public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message, IDictionary<string, object> htmlAttributes) {
        if (htmlHelper == null) {
            throw new ArgumentNullException("htmlHelper");
        }

        FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation();
        if (formContext == null && htmlHelper.ViewData.ModelState.IsValid) {
            return null;
        }

        string messageSpan;
        if (!String.IsNullOrEmpty(message)) {
            TagBuilder spanTag = new TagBuilder("span");
            spanTag.SetInnerText(message);
            messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine;
        }
        else {
            messageSpan = null;
        }

        StringBuilder htmlSummary = new StringBuilder();
        TagBuilder unorderedList = new TagBuilder("ul");

        IEnumerable<ModelState> modelStates = null;
        if (excludePropertyErrors) {
            ModelState ms;
            htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms);
            if (ms != null) {
                modelStates = new ModelState[] { ms };
            }
        }
        else {
            modelStates = htmlHelper.ViewData.ModelState.Values;
        }

        if (modelStates != null) {
            foreach (ModelState modelState in modelStates) {
                foreach (ModelError modelError in modelState.Errors) {
                    string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */);
                    if (!String.IsNullOrEmpty(errorText)) {
                        TagBuilder listItem = new TagBuilder("li");
                        listItem.SetInnerText(errorText);
                        htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));
                    }
                }
            }
        }

        if (htmlSummary.Length == 0) {
            htmlSummary.AppendLine(_hiddenListItem);
        }

        unorderedList.InnerHtml = htmlSummary.ToString();

        TagBuilder divBuilder = new TagBuilder("div");
        divBuilder.MergeAttributes(htmlAttributes);
        divBuilder.AddCssClass((htmlHelper.ViewData.ModelState.IsValid) ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName);
        divBuilder.InnerHtml = messageSpan + unorderedList.ToString(TagRenderMode.Normal);

        if (formContext != null) {
            // client val summaries need an ID
            divBuilder.GenerateId("validationSummary");
            formContext.ValidationSummaryId = divBuilder.Attributes["id"];
            formContext.ReplaceValidationSummary = !excludePropertyErrors;
        }
        return divBuilder.ToMvcHtmlString(TagRenderMode.Normal);
    }

ValidationSummaryValidCssClassName is "validation-summary-errors" and ValidationSummaryValidCssClassName is "validation-summary-valid".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM