Dec 1, 2011

Create a Custome valueprovider

Value providers are used by the model binding system in MVC to populate the values of model objects. MVC 3.0 includes value providers for several common value sources
System.Web.Mvc.FormValueProviderFactory
System.Web.Mvc.HttpFileCollectionValueProviderFactory
System.Web.Mvc.QueryStringValueProviderFactory
System.Web.Mvc.RouteDataValueProviderFactory

Decompile System.Web.Mvc.DefaultModelBinder, to review how BindProperty/BindModel (calls ContainsPrefix(text) on the value provider) and BindModel (GetValue) method uses Value Provider for populating model objects.

Below I have created a CookieValueProviderFactory derived from ValueProviderFactory which has a abstract method to GetValueProvider. In this case this gets my custome CookieValueProvider which implements IValueProvider (bool ContainsPrefix(string prefix) and System.Web.Mvc.ValueProviderResult GetValue(string key))

 public class CookieValueProviderFactory : ValueProviderFactory
    {
        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            return new CookieValueProvider(controllerContext.HttpContext.Request.Cookies);
        }

        private class CookieValueProvider : IValueProvider
        {

            private readonly HttpCookieCollection _cookieCollection;

            public CookieValueProvider(HttpCookieCollection cookieCollection)
            {
                _cookieCollection = cookieCollection;
            }

            public bool ContainsPrefix(string prefix)
            {
                return _cookieCollection[prefix] != null;
            }

            public ValueProviderResult GetValue(string key)
            {
                HttpCookie cookie = _cookieCollection[key];
                return cookie != null ?
                           new ValueProviderResult(cookie.Value,
                                       cookie.Value,
                                       CultureInfo.CurrentUICulture)
                           : null;
            }
        }
    }

Then I add this to the ValueProviderFactories like this

 protected void Application_Start()
 {
  ValueProviderFactories.Factories.Add(new CookieValueProviderFactory());
 }

To test this I added cookies and in the Action this was automatically binded.

 private void AddCookie(IUserData userData)
 {
  HttpContext.Response.Cookies.Add(
   new HttpCookie("somethingToCookies", "Anything")
   );
 }
 
 public ActionResult CreateEmployee(string somethingToCookies)
 {
        }
 

No comments:

Post a Comment