如何在验证摘要中添加图像以及错误消息?

时间:2011-07-12 05:01:19

标签: asp.net-mvc modelstate validationsummary

我想在验证摘要中显示带有成功图像(绿色勾号)和失败图像(红色警告)的错误消息。这该怎么做。 我验证摘要我将不得不显示一些粗体,斜体等文本,我试图传递这样的字符串。

inValid <b>username</b> or <b>password</b>

但是在页面中它的呈现原样。它没有以粗体显示用户名和密码。有没有办法做到这一点。我在控制器中收到此验证错误消息并将其添加到ModelState.add(错误);

2 个答案:

答案 0 :(得分:6)

ValidationSummary帮助程序HTML默认编码所有邮件。您可以编写一个不进行HTML编码的自定义帮助程序:

public static class HtmlExtensions
{
    public static MvcHtmlString MyValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message)
    {
        var formContext = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
        if (formContext == null && htmlHelper.ViewData.ModelState.IsValid)
        {
            return null;
        }

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

        var htmlSummary = new StringBuilder();
        var 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)
                {
                    var errorText = modelError.ErrorMessage;
                    if (!String.IsNullOrEmpty(errorText))
                    {
                        var listItem = new TagBuilder("li");
                        listItem.InnerHtml = errorText;
                        htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));
                    }
                }
            }
        }

        if (htmlSummary.Length == 0)
        {
            htmlSummary.AppendLine(@"<li style=""display:none""></li>");
        }

        unorderedList.InnerHtml = htmlSummary.ToString();

        var divBuilder = new TagBuilder("div");
        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 MvcHtmlString.Create(divBuilder.ToString(TagRenderMode.Normal));
    }
}

现在您可以在验证消息中使用HTML标记:

ModelState.AddModelError("user", "invalid <b>username</b> or <b>password</b>");

然后:

<%= Html.MyValidationSummary(true, null) %>

显然,通过这样做,您应该确保您的错误消息包含有效的HTML结构。

答案 1 :(得分:0)

毫无疑问,@ Darin Dimitrov的答案是最好的做法。但作为一个新手,我通过使用ViewBag来获得功能 在Controller

if(true) //All is well and success msg is to be sent
{
     ViewBag.Errors = null;
     ViewBag.Success = "<b>Login</b> is Successful";

     //Redirect
}
else
{
     ViewBag.Errors = "<b>Some Error messages</b>";
     ViewBag.Success = null;
 }

内部View()

@if(ViewBag.Errors != null)
{
     <div class="error">@Html.Raw(@ViewBag.Errors)</div>
}

@if(ViewBag.Success != null)
{
     <div class="success">@Html.Raw(@ViewBag.Success)</div>
}

现在是Css

.error { color: red; background-image:error_image.png; }
.success { color:green; background-image : success_image.png; }