Marc Marc - 29 days ago 4
C# Question

Convert querystring from/to object

I have this (simplified) class:

public class StarBuildParams
{
public int BaseNo { get; set; }
public int Width { get; set; }
}


And I have to transform instances of it to a querystring like this:

"BaseNo=5&Width=100"


Additionally I have to transform such a querystring back in an object of that class.

I know that this is pretty much what a modelbinder does, but I don't have the controller context in my situation (some deep buried class running in a thread).

So, is there a simple way to convert a object in a query string and back without having a controller context?

It would be great to use the modelbinding but I don't know how.

Answer

You can use reflection, something like this:

public T GetFromQueryString<T>() where T : new(){
    var obj = new T();
    var properties = typeof(T).GetProperties();
    foreach(var property in properties){
        var valueAsString = HttpContext.Current.Request.QueryString[property.PropertyName];
        var value = Parse( valueAsString, property.PropertyType);

        if(value == null)
            continue;

        property.SetValue(obj, value, null);
    }
    return obj;
 }

You'll need to implement the Parse method, just using int.Parse, decimal.Parse, DateTime.Parse, etc.

Comments