I'm using the MVC Validation nuget package called MVC Foolproof Validation.
I'm using it on my model to set a required to true if another model property was empty. The validation part works, as the ModelState is correctly set to invalid when the Id field and Location field are left empty. Inspecting the errors on the ModelState array I can see its working.
My problem is that the client side validation summary does not display. Here is how I've set things up. Can anyone spot my problem?
[DisplayName("Image Id")]
public string Id{ get; set; }
[DisplayName("Location Id")]
[RequiredIfEmpty("Id", ErrorMessage = "You must..etc"]
public string LocationId{ get; set; }
In my view I'm setting up the validation summary and inputs as follows
<div class="form-horizontal">
<hr/>
@Html.ValidationSummary(true, "", new {@class = "text-danger"})
<div class="form-group">
@Html.LabelFor(model => model.SearchCriteria.Id, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.SearchCriteria.Id, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.SearchCriteria.Id, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.SearchCriteria.LocationId, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.SearchCriteria.LocationId, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.SearchCriteria.LocationId,"", new {@class = "text-danger"})
</div>
</div>
In my controller action I'm checking the Model state. Do I need to call ModelState.AddModelError(..). I've tried that but perhaps there is a way I need to call it.
[HttpPost]
public ActionResult Search(SearchCriteria searchCriteria)
{
var searchViewModel = new SearchViewModel
{
SearchCriteria = searchCriteria
};
if (ModelState.IsValid)
{
...
}
//ModelState.AddModelError("LocationId", "test");
return View(searchViewModel);
}
@Html.ValidationSummary(true, ..)means it excludes property level errors. But you already have@Html.ValidationMessageFor(model => model.SearchCriteria.LocationId, ...)which will display the error mesage at that location ifIdisnulland you do not provide a value forLocationId. And if you have set this up correctly, the error message will be dsplayed and you form will not even be able to be submitted if its invalid so the fact you hitting the controller method suggest other problems - user3559349SearchCriteriawhen the model in your view does not appear to be@model SearchCriteriasuggest even more problems - user3559349