Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newline in a ValidationMessage

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>
like image 233
sander Avatar asked Oct 16 '12 07:10

sander


2 Answers

You can do it with this one liner:

@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationMessageFor(m => m.Property).ToHtmlString()))
like image 142
Leniel Maccaferri Avatar answered Sep 18 '22 14:09

Leniel Maccaferri


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.

like image 34
Darin Dimitrov Avatar answered Sep 22 '22 14:09

Darin Dimitrov