Hi all,
I have a question regarding the method i am using for doing Business Rule Validations in asp.net mvc.
Currently i have an exception class that looks something like this
public class ValidationException : Exception
{
private ModelStateDictionary State { get; set; }
public ValidationException(ModelStateDictionary state)
{
State = state;
}
public void MergeModelStates(ModelStateDictionary state)
{
state.Merge(this.State);
}
}
and a validator that looks like this
public void Validate(IEntity entity)
{
ModelStateDictionary state = new ModelStateDictionary();
if (entity.Contact != null && _service.GetBy(entity.Contact.Id) == null)
state.AddModelError("Contact", "Invalid Contact.");
if (entity.Title.Length > 8)
state.AddModelError("title", "Title is too long...");
... etc
if (!state.IsValid)
throw new ValidationException(state);
}
and a Controller That does something like this
public ActionResult Add()
{
var entity = new InputModel;
try
{
TryUpdateMode(inputModel);
..... Send input to a Repository (Repository calls Validate(entity);
}
catch (ValidationException validationException)
{
validationException.MergeModelStates(this.ModelState);
TryUpdateModel(inputModel);
return View("Add",inputModel);
}
return View("List");
}
Is it wrong to use an exception to do something like this? Are there examples of a better method? I don't really want to add the validation to the Model Entity itself. The only other way i've seen it done is to inject the Controllers ModelState to the Repository layer, but that seemed sloppy to me.
Thanks for any help