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.
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.
But anyway, if you want to send as query string you can do following: Convert object into string. Encode string. Append as parameter.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With