ValidationMessage中的换行符

san*_*der 13 asp.net-mvc newline line-breaks asp.net-mvc-3 validationmessage

我正在测试一个null列表.每次我找到一个,我都将它保存在一个数组中,以在验证消息中实现它.

我想要的输出看起来像这样:

需要字段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 };
Run Code Online (Sandbox Code Playgroud)

此处处理此异常:

catch (CustomException ex)
{                   
    ModelState.AddModelError("file", ex.GetExceptionString());
    return View("theView");
}    
Run Code Online (Sandbox Code Playgroud)

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;        
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

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

Len*_*rri 16

你可以用这个衬里做到这一点:

@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationMessageFor(m => m.Property).ToHtmlString()))
Run Code Online (Sandbox Code Playgroud)

  • +1 Smart,这非常适合我和作者寻找的简单而简短的修复. (5认同)
  • 我已将它用于验证摘要,如@if(Html.ValidationSummary(true)!= null){@ Html.Raw(HttpUtility.HtmlDecode(Html.ValidationSummary(true).ToString())); } (2认同)
  • +1这应该是正确的答案!我同意@sander没有人愿意为换行添加50行代码! (2认同)

Dar*_*rov 8

您需要编写自定义帮助程序才能实现此目的.内置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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

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

并在视图中:

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

如果您想在ValidationSummary中显示错误消息,您还可以编写一个自定义帮助程序,它不会像我所示的那样对错误消息进行HTML编码this post.

  • 我找到了一些关于扩展的线程.但是,要实现一些如此基本的东西,感觉真是太多了.我只是想检查一下我是否有另一种方式. (4认同)
  • 写一个<br /> ...有点;)并不是我不想这样做.我认为一个优秀的程序员应该"保持简单".获得新行的50行代码并不像保持简单.这就是为什么我想检查是否没有其他方式. (2认同)