将对象转换为url编码字符串

3
我有一个类
class Example
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }
    public String Prop3 { get; set; }
}

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

Url编码字符串:
prop1=val1&prop2=val2&prop3=val3

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


我认为负投票的意思是“你应该写出你的场景”。你为什么想要这样做?你想在哪里使用它?标题是“对象到URL”,标签是“asp.net-mvc”,在MVC中,最好的方法是@Darin的建议。因为UrlHelper就是为此而设计的。所以你的问题不够清楚。希望你能理解... - AliRıza Adıyahşi
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

如果您需要绝对URL,请使用proper overload

string url = Url.Action("index", "home", model, "http");

2
这只能在MVC上运行,对吧? - James Poulose
1
当然会工作,为什么不会呢? - Darin Dimitrov

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());
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接