3

我有一堂课

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

如何自动将此对象转换为 urlencoded 字符串,然后将其附加到我的主机名?

Urlencoded 字符串:
prop1=val1&prop2=val2&prop3=val3

最后结果:
http://example.com?prop1=val1&prop2=val2&prop3=val3

4

2 回答 2

8

您可以使用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

如果你想要一个绝对网址,只需使用proper overload

string url = Url.Action("index", "home", model, "http");
于 2013-03-05T07:26:41.773 回答
0

如果您使用的是 Asp.Net MVC,那么只需将 FormMethod 更改为 GET。否则,如果你想在代码中使用反射。(如下)

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());
    }
}
于 2013-03-05T07:36:26.170 回答