I believe you are looking to customize the error message on your view. You can customize the error messages including the ones you added using ModelState.AddModelError("", "error message") in three ways.
Option 1
Use Html.ValidationSummary() and customize its look via the validation-summary-errors class. The default mvc project template in VS will include that class by default. It has a default color of red (I think). But you can practically control every aspect of the error summary by changing that class.
.validation-summary-errors {
border: 5px solid red; // thick red border
color: #3904D9; // dark blue
font-size: 1.5em; // quite big fonts
font-weight: bold;
}
Option 2
The ValidationSummary outputs the messages in an unordered list (li). If your project calls for a different way of showing the error messages, you can do it on the view by inspecting the ViewDataDictionary. The following code will write the error messages in separate divs with a thin red border. The style is written inline to make the sample simple.
@foreach (var item in ViewData.ModelState) {
if (item.Value.Errors.Any()) {
foreach (ModelError e in item.Value.Errors) {
<div style="border: 1px solid red;margin-bottom:5px;">
@e.ErrorMessage</div>
}
}
}
Option 3
If you do not want to put logic on your view, then you can extend the htmlhelper (or create a custom helper). You basically will use the same logic shown in Option 2 in the custom htmlhelper.
public static class HtmlExtensions {
public static MvcHtmlString CustomValidationSummary(this HtmlHelper helper)
{
var html = string.Empty;
foreach (var item in helper.ViewData.ModelState)
{
if (item.Value.Errors.Any()) {
foreach (ModelError e in item.Value.Errors) {
html
+= "<div style='border: 1px solid red;margin-bottom:5px;'>"
+ e.ErrorMessage
+ "</div>";
}
}
}
return MvcHtmlString.Create(html);
}
}
And then you use it the same way as you will use the ValidationSummary:
@Html.CustomValidationSummary()