换行的ValidationMessage [英] Newline in a ValidationMessage

查看:524
本文介绍了换行的ValidationMessage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

输出我想是这样的:

字段1是必需的

4场需要

等等...

但我不能似乎能够启动一个新行。

现在,它看起来像这样:

字段1项为必填项4要求

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

编辑:

控制器:

 的IDictionary< INT,字符串> emptyFields =新词典< INT,字符串>();的foreach(在AnotherThing.Collection东西嘛)
{
    如果(thing.Property == NULL)
        emptyFields.add(thing.Index,thing.Name);
}如果(emptyFields.Any())
    抛出新CustomException(){EmptyFields = emptyFields};

这异常这里处理:

 赶上(CustomException前)
{
    ModelState.AddModelError(文件,ex.GetExceptionString());
    返回视图(theView);
}

CustomException:

 公共类CustomException:异常
{
    公众的IDictionary< INT,字符串> EmptyFields {搞定;组; }
    公众覆盖字符串标签{{返回someLabel }}
    公众覆盖字符串GetExceptionString()
    {
        弦乐味精=;
        的foreach(KeyValuePair< INT,字符串> ELEM在EmptyFields)
        {
            味精+ =行:+(elem.Key + 1)的ToString()+栏:+ elem.Value +< BR />中;
        }
        返回味精;
    }
}

查看:

 <跨度风格=COLOR:#FF0000> @ Html.Raw(Html.ValidationMessage(文件)的ToString())< / SPAN>


解决方案

您将需要编写一个定制的帮手实现这一目标。内置的 ValidationMessageFor 助手会自动连接HTML codeS的值。这里有一个例子:

 公共静态类ValidationMessageExtensions
{
    公共静态IHtmlString MyValidationMessageFor<的TModel,TProperty>(
        这与的HtmlHelper LT;的TModel>的HtmlHelper,
        防爆pression<&Func键LT;的TModel,TProperty>>恩
    )
    {
        VAR htmlAttributes =新RouteValueDictionary();
        字符串validationMessage = NULL;
        VAR前pression =前pressionHelper.GetEx pressionText(除息);
        VAR MODELNAME = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(如pression);
        VAR formContext = htmlHelper.ViewContext.ClientValidationEnabled? htmlHelper.ViewContext.FormContext:空;
        如果(htmlHelper.ViewData.ModelState.ContainsKey(MODELNAME)及!&安培; formContext == NULL)
        {
            返回null;
        }        VAR的ModelState = htmlHelper.ViewData.ModelState [MODELNAME]
        VAR modelErrors =(ModelState中== NULL)?空:modelState.Errors;
        VAR modelError =(((modelErrors == NULL)||(modelErrors.Count == 0))
            ?空值
            :modelErrors.FirstOrDefault(!M => String.IsNullOrEmpty(m.ErrorMessage))? modelErrors [0]);        如果(modelError == NULL和放大器;&安培; formContext == NULL)
        {
            返回null;
        }        VAR建设者=新TagBuilder(跨度);
        builder.MergeAttributes(htmlAttributes);
        builder.AddCssClass((modelError = NULL)HtmlHelper.ValidationMessageCssClassName!?HtmlHelper.ValidationMessageValidCssClassName);        如果(!String.IsNullOrEmpty(validationMessage))
        {
            builder.InnerHtml = validationMessage;
        }
        否则,如果(modelError!= NULL)
        {
            builder.InnerHtml = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext,modelError,ModelState中);
        }        如果(formContext!= NULL)
        {
            布尔replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage);
            builder.MergeAttribute(数据valmsg换,MODELNAME);
            builder.MergeAttribute(数据valmsg替换,replaceValidationMessageContents.ToString()ToLowerInvariant());
        }        返回新HtmlString(builder.ToString(TagRenderMode.Normal));
    }    私人静态字符串GetUserErrorMessageOrDefault(HttpContextBase HttpContext的,ModelError错误的ModelState ModelState中)
    {
        如果(!String.IsNullOrEmpty(error.ErrorMessage))
        {
            返回error.ErrorMessage;
        }
        如果(ModelState中== NULL)
        {
            返回null;
        }        VAR attemptedValue =(modelState.Value!= NULL)? modelState.Value.AttemptedValue:空;
        返回的String.Format(CultureInfo.CurrentCulture,值{0}不适用于财产,attemptedValue);
    }
}

和则:

 公共类MyViewModel
{
    [必需(的ErrorMessage =错误线路1< BR />错误的2号线)]
    公共字符串SomeProperty {搞定;组; }
}

和视图:

  @model MyViewModel
@using(Html.BeginForm())
{
    @ Html.EditorFor(X => x.SomeProperty)
    @ Html.MyValidationMessageFor(X => x.SomeProperty)
    <按钮式=提交>确定< /按钮>
}

如果你想显示错误消息中的ValidationSummary,你也可以这样写,不会HTML EN code中的错误消息,因为我在的 这个帖子

I'm testing a list of things for null. Every time I find one, I save it in an array to implement it in a validationmessage.

Output I want looks like this:

Field 1 is required
Field 4 is required
etc...

But I can't seem to be able to start a new line.

Now, it looks like this:

Field 1 is required Field 4 is required

Does anybody know how to achieve this?

EDIT:

controller:

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 };

This exception is handled here:

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;        
    }
}

view:

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

解决方案

You will need to write a custom helper to achieve that. The built-in ValidationMessageFor helper automatically HTML encodes the value. Here's an example:

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);
    }
}

and then:

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

and in the view:

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

And if you want to display the error message in a ValidationSummary you could also write a custom helper that will not HTML encode the error message as I have shown in this post.

这篇关于换行的ValidationMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆