Quantcast
Channel: Sankarsan's Journal
Viewing all articles
Browse latest Browse all 42

ASP.NET 4.5 Web Forms ModelBinding – Custom Value Providers

$
0
0

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:

image

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

image

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

image

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

image

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:

image

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:

image

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.

image

Now the data comes up in Firefox as shown below:

image



Viewing all articles
Browse latest Browse all 42

Trending Articles