换行的ValidationMessage(Newline in a ValidationMessag

2019-08-01 12:52发布

我测试的东西空的列表。 每次我找到一个,我把它保存在一个数组来实现它在validationmessage。

输出我想是这样的:

现场1需要
场4是必需
等等...

但我似乎无法能够启动新行。

现在,它看起来像这样:

字段1需要字段4是必需

有谁知道如何实现这一目标?

编辑:

控制器:

IDictionary<int, String> emptyFields = new Dictionary<int, String>();

foreach (Something thing in AnotherThing.Collection)
{
    if (thing.Property == null)
        emptyFields.add(thing.Index, thing.Name);                   
}

if (emptyFields.Any())
    throw new CustomException() { EmptyFields = emptyFields };

此异常这里处理:

catch (CustomException ex)
{                   
    ModelState.AddModelError("file", ex.GetExceptionString());
    return View("theView");
}    

CustomException:

public class CustomException: Exception
{
    public IDictionary<int,String> EmptyFields { get; set; }
    public override String Label { get { return "someLabel"; } }
    public override String GetExceptionString()
    {
        String msg = "";
        foreach (KeyValuePair<int,String> elem in EmptyFields)
        {
            msg += "row: " + (elem.Key + 1).ToString() + " column: " + elem.Value + "<br/>";      
        }
        return msg;        
    }
}

视图:

<span style="color: #FF0000">@Html.Raw(Html.ValidationMessage("file").ToString())</span>

Answer 1:

你可以用这一个班轮做到这一点:

@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationMessageFor(m => m.Property).ToHtmlString()))


Answer 2:

你需要编写自定义助手实现这一目标。 内置ValidationMessageFor助手自动HTML编码值。 下面是一个例子:

public static class ValidationMessageExtensions
{
    public static IHtmlString MyValidationMessageFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> ex
    )
    {
        var htmlAttributes = new RouteValueDictionary();
        string validationMessage = null;
        var expression = ExpressionHelper.GetExpressionText(ex);
        var modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
        var formContext = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
        if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName) && formContext == null)
        {
            return null;
        }

        var modelState = htmlHelper.ViewData.ModelState[modelName];
        var modelErrors = (modelState == null) ? null : modelState.Errors;
        var modelError = (((modelErrors == null) || (modelErrors.Count == 0)) 
            ? null 
            : modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]);

        if (modelError == null && formContext == null)
        {
            return null;
        }

        var builder = new TagBuilder("span");
        builder.MergeAttributes(htmlAttributes);
        builder.AddCssClass((modelError != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName);

        if (!String.IsNullOrEmpty(validationMessage))
        {
            builder.InnerHtml = validationMessage;
        }
        else if (modelError != null)
        {
            builder.InnerHtml = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState);
        }

        if (formContext != null)
        {
            bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage);
            builder.MergeAttribute("data-valmsg-for", modelName);
            builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());
        }

        return new HtmlString(builder.ToString(TagRenderMode.Normal));
    }

    private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState)
    {
        if (!String.IsNullOrEmpty(error.ErrorMessage))
        {
            return error.ErrorMessage;
        }
        if (modelState == null)
        {
            return null;
        }

        var attemptedValue = (modelState.Value != null) ? modelState.Value.AttemptedValue : null;
        return string.Format(CultureInfo.CurrentCulture, "Value '{0}' not valid for property", attemptedValue);
    }
}

然后:

public class MyViewModel
{
    [Required(ErrorMessage = "Error Line1<br/>Error Line2")]
    public string SomeProperty { get; set; }
}

并在视图:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.SomeProperty)
    @Html.MyValidationMessageFor(x => x.SomeProperty)
    <button type="submit">OK</button>
}

如果你想显示错误消息中的ValidationSummary你也可以写一个自定义的助手,不会HTML编码错误消息,因为我在证明this post



Answer 3:

试试这个

附加
每个错误消息后标签,并使用Html.Raw()方法来显示内容Html.Raw将解码HtmlContent。

you message like 
 Field 1 is required <br/>Field 4 is required<br/> 

In View

Html.Raw("Yore Error Message")


Answer 4:

如果有人正在寻找它,这里是如何为验证摘要做到这一点:

@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationSummary(true).ToHtmlString()))


Answer 5:

你在验证摘要显示它们? 我不认为它支持换行等。我想创建一个基于HTML显示验证摘要的自定义HTML帮助HTML。

这同样适用于validationmessage所以可能需要做出一个自定义的帮手



Answer 6:

我要做的就是一群人在一个div

       <div class="Errors">

        @Html.ValidationMessageFor(m => m.Name)<br/>
        @Html.ValidationMessageFor(m => m.LName)<br />
      </div>

然后创建一个类

     .Errors {
          color: red;
          font-size: 10px;
          font-weight: bold;
          }

但如果你想要做一个多错误,那么什么Leinel提到的是最好的way.the原因,我帮他们一些用户将不会看到错误长的形式和他们就会开始给我们打电话.. ^^,



文章来源: Newline in a ValidationMessage