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