Get ModelState Validation from Service Using Ioc and a Validation Wrapper for MVC

I googeled and binged till my fingers were tired, tinkered with varying redesigns of unity and windsor but could not find a clean way to get my ModelState Validation information back into my controller ModelState cleanly.  So following the ethic of "whatever works" here you are for the brave.

First you need to actually get the model state, my service passes back a true false or a zero if there was a problem as it handles and records all errors that happen behind it.  So if I know something went wrong then to get the model state I used the code below.  This goes at the top of the service class.

   1: public ModelStateDictionary GetModelStateDictionary()
   2: {
   3:     return ((MvcCms.Service.Validation.ModelStateWrapper)_validationDictionary)._modelState;
   4: }

Then to merge that into the controllers ModelState

   1: int createdCategoryId = _cmsService.CreateContentCategory(contentCategoryToCreate);
   2: if (createdCategoryId == 0)
   3: {
   4:     var modelState = _cmsService.GetModelStateDictionary();
   5:     this.ModelState.Merge(modelState); 
   6:     
   7:     ViewData["message"] = "";
   8:     return View("CreateContentCategory");
   9: }

Which calls the merge code below.

   1: public static class ModelExtensions
   2: {
   3:     public static bool HasValue(this string value)
   4:     {
   5:         return !string.IsNullOrEmpty(value) && value.Trim().Length > 0;
   6:     }
   7:  
   8:     public static void Merge(this ModelStateDictionary controllerModelState, ModelStateDictionary serviceModelState)
   9:     {
  10:         Guard.AgainstNullParameter(controllerModelState, "modelState");
  11:         Guard.AgainstNullParameter(controllerModelState, "dictionary");
  12:  
  13:         foreach (var item in serviceModelState)
  14:         {
  15:             foreach (var keyItem in item.Value.Errors)
  16:             {
  17:                 controllerModelState.AddModelError(item.Key, keyItem.ErrorMessage);
  18:             }
  19:         }
  20:     }
  21: }
  22:  
  23: public static class Guard
  24: {
  25:     public static void AgainstNullParameter(object parameter, string parameterName)
  26:     {
  27:         if (parameter == null) throw new ArgumentNullException(parameterName);
  28:     }
  29: } 
Is it gorgeous?  Well as an NCAA coach nearby recently said, "there is no such thing as an ugly win"  LOL.
Comments refreshcmnts
You must be Loged On to make a comment.
Edit Comment

Please wait... loading

Reply To Comment

Please wait... loading