Daily Archives: January 7, 2014

Extract object from posted data in asp.net

Here in this post I am going to demo a class which helps extracting object from NameValueCollection.

This class has one generic method called Extract which accept NameValueCollection as parameter. It loops through the collection and find matching property and fill it’s value from collection. It can further be enhanced to extract nested/complex object type.

Class

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Web;

namespace MSCoder.ObjectExtractorSample
{
    public static class Extractor
    {
        public static T Extract<T>(NameValueCollection collection)
        {
            T result = (T)Activator.CreateInstance(typeof(T));

            foreach (var item in collection)
            {
                if (item.ToString().StartsWith("__"))
                    continue;

                PropertyInfo prop = (typeof(T)).GetProperty(item.ToString(), BindingFlags.Public | BindingFlags.Instance);

                if (null != prop && prop.CanWrite)
                {
                    switch (prop.PropertyType.Name)
                    {
                        case "Boolean":
                            prop.SetValue(result, Convert.ToBoolean(Convert.ToInt16(collection[item.ToString()])), null);
                            break;

                        case "String":
                            prop.SetValue(result, collection[item.ToString()], null);
                            break;

                        case "Int32":
                            prop.SetValue(result, Convert.ToInt32(collection[item.ToString()]), null);
                            break;

                        case "Int64":
                            prop.SetValue(result, Convert.ToInt64(collection[item.ToString()]), null);
                            break;

                        case "Int16":
                            prop.SetValue(result, Convert.ToInt16(collection[item.ToString()]), null);
                            break;

                        case "DateTime":
                            prop.SetValue(result, Convert.ToDateTime(collection[item.ToString()]), null);
                            break;

                        default:
                            break;
                    }
                }
            }

            return result;
        }
    }
}

Just to demo I have created a Person class as shown below.

class

 

 

I have added 4 controls on my page as shown below to get values from each control and prepare person object.

forms

How to use it

code

Download Code

 

Happy Coding

MSCoder