ASP.NET 4.5 Web Forms ModelBinding – Custom Value Providers

Posted: December 8, 2012 in .NET, ASP.NET
Tags: , ,

ASP.NET 4.5 has introduced model binding and strongly typed templates for ASP.NET server controls.This simplifies the way a plain .NET object can be bound as a datasource of a server control like a GridView.Let’s get started off with a simple example of how model binding works.

The snippet below is our model class:


The way the model is bound to the GridView is shown below


Now we need to implement the “SelectMethod” GetData as shown below. This returns a hard coded list of “Data” objects.


This runs fine and data shows up in the browser as shown below:


Now suppose, we need to filter the data. Obviously, we will try to filter the data based on some input from the browser which can be querystring value,form values, cookies, viewstate, etc.This is where the “value providers” comes into picture.The “value providers” extract data from request and bind them to a parameter of the “SelectMethod” as runtime, so that they can be used to manipulate the data.There are value providers already available querystring, controls, form values, cookies etc.In this post we will try to build a custom value provider which is able to extract values from Http headers in the request.

To create a value provider we first need to have a class which provides an implementation of the System.Web.ModelBinding.IValueProvider interface. This interface provides a method

  • ValueProviderResult GetValue(string key) – This method is supposed to return the value based a on specified key. The System.Web.ModelBinding.ValueProviderResult is a class that wraps the value retrieved by the value provider.

Our implementation is as shown below:


The next step is to create an attribute which can be applied to the parameters. This is done by deriving from the base class System.Web.ModelBinding.ValueProviderSourceAttribute class and overriding it’s two following methods:

  • public abstract IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)– This method returns an instance of the IValueProvider implementation.
  • public virtual string GetModelName() – This method returns the name of the “key” whose value is to be retrieved.

The implementation is shown below:


Now we will modify the “SelectMethod” GetData as shown below. Here the HttpHeaderAttribute is applied on the parameter “key”. So the value of the HTTP Header User-Agent is bound to the parameter “key” by HttpHeaderProvider.


Now the data comes up in Firefox as shown below:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s