Im following the approch outlined here to do this.
Im having a problem with validating a dropdown selection with xval, the MVC binding seems to infer the wrong thing an allowing the operation to pass validation, but the modelstate stores the binding exception and makes the page invalid - so I get the situation where operation is allowed to execute with invalid data, but the page is invalid so the user is lead to believe validation failed.
This might make it clearer
This is my drop down, assume the user did nothing so "Please select" is selected.
Do you like cheese:
<select name="Favourites.Cheese">
<option>Please Select</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
<%=Html.ValidationMessage("Favourites.Cheese")%>
This is the Controller action the from posts too, MVC maps the value false to fav.cheese,
public ActionResult Create(Favourites fav)
{
try
{
_favTask.Create(fav);
}
catch (RulesException ex)
{
ex.AddModelStateErrors(ModelState, "Favourites");
}
if(!ModelState.IsValid)
{
//redirect back
}
//other stuff
}
The property has been attributed
pulic class Favourites
{
[Required]
public bool Cheese{get;set;}
}
No exceptions are throw because fav.cheese has a value
public int Create(Favourites fav)
{
var errors = DataAnnotationsValidationRunner.GetErrors(fav);
if (errors.Any())
throw new RulesException(errors);
//create fav
}
But when focus returns to the controller ModelState.Isvalid comes out as false, so the from is reloaded with the message The value 'Please Select' is invalid. How do I stop this, from happening and how do I xVal driven validation method of "Please select a value"?