We have recently upgraded our application to ASP.NET MVC 4 and the server side validation stopped working on it.
I created a new ASP.NET MVC 4 application with a dummy model with a validation that works fine but same does not in the upgraded application.
Model:
public class TestValidation
{
[Required(ErrorMessage = @"Name is required")]
public string Name
{
get;
set;
}
[Required(ErrorMessage = @"Employment account required")]
[DisplayName("Employee")]
public string EmploymentAccount
{
get;
set;
}
}
Controller:
public class ValidationController : Controller
{
//
// GET: /Validation/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(TestValidation model)
{
if (ModelState.IsValid)
{
return View("Index");
}
return View(model);
}
}
View:
@model MVC4.Models.TestValidation
@using (Html.BeginForm("Index", "Validation", FormMethod.Post, new {id = "AuditPaperworkForm"}))
{
<div class="form-group">
@Html.LabelFor(m => m.Name, new {@class = "col-md-2 control-label"})
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.EmploymentAccount, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.EmploymentAccount, new { @class = "form-control" })
@Html.ValidationMessageFor(x=>x.EmploymentAccount)
</div>
</div>
<input type="submit" class="btn btn-default" value="Register" />
}
NOTE: Before the upgrade the application was on ASP.NET MVC 3. The validation is not working on the string properties and for the rest of them it is throwing the default error message "Value is Required" instead of the custom message I am putting in the attribute.