Saturday, February 18, 2012

MVC strip mask characters

In Previous post,I created masked inputs but on form post,it is posting mask characters as well. We can strip these characters using ModelBinders and thus can post numeric data only.
Common\ModelBinders\StripMaskCharacters.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. using MvcLists.Common.CustomAttributes;
  8.  
  9. namespace MvcLists.Common.ModelBinders
  10. {
  11.     public class StripMaskCharacters : DefaultModelBinder
  12.     {
  13.         protected override void SetProperty(ControllerContext controllerContext,
  14.                                             ModelBindingContext bindingContext,
  15.                                             System.ComponentModel.PropertyDescriptor propertyDescriptor,
  16.                                             object value)
  17.         {
  18.            if(value!=null && propertyDescriptor.PropertyType==(typeof(string)))
  19.            {
  20.                value = ((string) value).Trim();
  21.                if ((string)value == string.Empty)
  22.                {
  23.                    value = null;
  24.                }
  25.                else if(propertyDescriptor.Attributes[typeof(MaskAttribute)]!=null
  26.                    && bindingContext.ValueProvider.GetValue(propertyDescriptor.Name)!=null
  27.                    && bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue!=null)
  28.                {
  29.                    value = Regex.Replace(bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue,
  30.                                          "[^0-9]", string.Empty);
  31.                }
  32.            }
  33.             base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
  34.         }
  35.     }
  36. }
Then register this model binder in Application_Start of global.asax
Global.asax
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Web.Routing;
  7. using FluentValidation.Mvc;
  8. using MvcLists.Common.DataAnnotations;
  9. using MvcLists.Common.ModelBinders;
  10.  
  11. namespace MvcLists
  12. {
  13.     // Note: For instructions on enabling IIS6 or IIS7 classic mode,
  14.     // visit http://go.microsoft.com/?LinkId=9394801
  15.  
  16.     public class MvcApplication : System.Web.HttpApplication
  17.     {
  18.         public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  19.         {
  20.             filters.Add(new HandleErrorAttribute());
  21.         }
  22.  
  23.         public static void RegisterRoutes(RouteCollection routes)
  24.         {
  25.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  26.  
  27.             routes.MapRoute(
  28.                 "Default", // Route name
  29.                 "{controller}/{action}/{id}", // URL with parameters
  30.                 new { controller = "Person", action = "Index", id = UrlParameter.Optional } // Parameter defaults
  31.             );
  32.  
  33.         }
  34.  
  35.         protected void Application_Start()
  36.         {
  37.             AreaRegistration.RegisterAllAreas();
  38.  
  39.             RegisterGlobalFilters(GlobalFilters.Filters);
  40.             RegisterRoutes(RouteTable.Routes);
  41.             ModelMetadataProviders.Current=new MyModelMetaDataProvider();
  42.             ModelBinders.Binders.DefaultBinder = new StripMaskCharacters();
  43.             FluentValidationModelValidatorProvider.Configure();
  44.         }
  45.         protected void Application_BeginRequest()
  46.         {
  47.             HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
  48.             HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
  49.             HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
  50.             HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
  51.             HttpContext.Current.Response.Cache.SetNoStore();
  52.  
  53.         }
  54.     }
  55. }

No comments: