Newline in a ValidationMessage

sander picture sander · Oct 16, 2012 · Viewed 12.2k times · Source

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>

Answer

Leniel Maccaferri picture Leniel Maccaferri · Oct 1, 2013

You can do it with this one liner:

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