Is it possible to add a specific error message to a field in a view? Currently I have validation on the model to check whether a field is empty (ValidationMessageFor<>) and I am using validation summary for specific errors. What I'm wondering is whether the specific error message created for the summary can replace the ValidationMessageFor<>?
Model:
[Required]
public string SchoolCode { get; set; }
View:
@Html.ValidationSummary("", new { @class = "text-danger" })
@Html.EditorFor(m => m.SchoolCode, new { htmlAttributes = new { @class = "form-control", @placeholder = "School Code" } })
@Html.ValidationMessageFor(model => model.SchoolCode, "", new { @class = "text-danger" })
Controller:
var schoolExists = RepositoryHelper.GetSchoolByCode(model.SchoolCode);
if (schoolExists == null)
{
ModelState.AddModelError(string.Empty, @"No school exists with this code");
return View(model);
}
if (ModelState.IsValid)
{
//do other stuff
}
So if the model state isn't valid it returns the model error, but if an incorrect code is entered it adds "No school exists with this code" to the validation summary. Could I replace the school code model error with the school code summary error?