I have been trying to display validation errors using MVC's inherent validation framework. I am using following code for my Controller:
[HttpPost]
public ActionResult SaveApplication(ApplicationModel application)
{
if (!ModelState.IsValid)
{
return View("New",application);
}
ApplicationBLL.SaveApplication(application);
return Content(string.Empty);
}
While my view looks like:
<tr>
<td>Name</td>
@Html.ValidationSummary(true)
<td>@Html.TextBoxFor(m => m.Name)</td>
<td>@Html.ValidationMessageFor(m => m.Name, "Name is required")</td>
</tr>
following is how the model class looks like:
public class ApplicationModel
{
public int ApplicationId { get; set; }
public string ApplicationNumber { get; set; }
[Required]
public string Name { get; set; }
public DateTime EventDate { get; set; }
public string EventAddress { get; set; }
}
My Model has [Required] validation on the name property and when I put debugger on my controller, it recognizes that the ModelState is not valid and returns back to the view but I do not see any errors on my page. I may be missing something very trivial since this is my first time using MVC's validation framework.
One thing I would like to add is that I am calling Controller with an Ajax Post Can that be contributing to this anomaly?
[Required(ErrorMessage = "Name is required")] public string Name { get; set; }In the view use just@Html.ValidationMessageFor(m => m.Name)and in the controller justif (!ModelState.IsValid) { return View(application); }. If you submit the form with no text in the Name control, you will see the error message (and if client side validation is enabled and the scripts included - the message will be displayed and it wont even submit)ApplicationModelviewmodel class.