Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 862
Marc Avatar asked Mar 22 '12 06:03

Marc


People also ask

How do you turn a URL into an object?

Use the URLSearchParams constructor to convert a query string to an object, e.g. const obj = new URLSearchParams('? page=3&filter=js') . The constructor returns an object instance from which we can access the query string parameters using the get() method, e.g. obj.

Can we send object in query string C#?

But anyway, if you want to send as query string you can do following: Convert object into string. Encode string. Append as parameter.

How do I pass QueryString?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.


2 Answers

A solution with Newtonsoft Json serializer and linq:

string responseString = "BaseNo=5&Width=100"; var dict = HttpUtility.ParseQueryString(responseString); string json = JsonConvert.SerializeObject(dict.Cast<string>().ToDictionary(k => k, v => dict[v])); StarBuildParams respObj = JsonConvert.DeserializeObject<StarBuildParams>(json); 
like image 189
ACM Avatar answered Sep 21 '22 10:09

ACM


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.

like image 29
Ivo Avatar answered Sep 23 '22 10:09

Ivo