3

I have a class

class Example
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }
    public String Prop3 { get; set; }
}

How can I automagically convert this object to a urlencoded string and then append it to my hostname?

Urlencoded string:
prop1=val1&prop2=val2&prop3=val3

Final result:
http://example.com?prop1=val1&prop2=val2&prop3=val3

ryandawkins
  • 1,537
  • 5
  • 25
  • 38
user1644160
  • 277
  • 2
  • 6
  • 12
  • I think downvotes mean "you should write your scenerio". Why you want to do this. Where you want to use this? Title is "object to url", tag is "asp.net-mvc", in MVC the best way is the @Darin suggestion. Because UrlHelper is designed to do this.So your question not clear enough. I hope you understand... – AliRıza Adıyahşi Mar 05 '13 at 07:39

2 Answers2

8

You could use an UrlHelper:

var model = new MyClass
{
    Prop1 = 1,
    Prop2 = 2,
    Prop3 = "prop 3"
};
string url = Url.Action("index", "home", model);
// will generate /?Prop1=1&Prop2=2&Prop3=prop%203

And if you want an absolute url just use the proper overload:

string url = Url.Action("index", "home", model, "http");
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

If you are using Asp.Net MVC, then just change the FormMethod to GET. else, if you want to in code you can use reflection. (as follows)

public class TestModel
{
    [Required]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }

    public string Test()
    {
        TestModel model=new TestModel(){Name="Manas",Id=1};
        Type t = model.GetType();
        NameValueCollection nvc=new NameValueCollection();
        foreach (var p in t.GetProperties())
        {
            var name = p.Name;
            var value=p.GetValue(model,null).ToString();
            nvc.Add(name, value);
        }

       var result= ConstructQueryString(nvc);
       return result;
    }
    public string ConstructQueryString(NameValueCollection Params)
    {
        List<string> items = new List<string>();
        foreach (string name in Params)
            items.Add(String.Concat(name, "=", HttpUtility.UrlEncode(Params[name])));
        return string.Join("&", items.ToArray());
    }
}
Manas
  • 2,534
  • 20
  • 21