asp.net – 如何将一个对象序列化为查询字符串格式?
发布时间:2020-12-15 19:42:06 所属栏目:asp.Net 来源:网络整理
导读:如何将对象序列化为查询字符串格式?我似乎找不到在谷歌的答案。谢谢。 这里是我将序列化的对象作为一个例子。 public class EditListItemActionModel{ public int? Id { get; set; } public int State { get; set; } public string Prefix { get; set; } pu
如何将对象序列化为查询字符串格式?我似乎找不到在谷歌的答案。谢谢。
这里是我将序列化的对象作为一个例子。 public class EditListItemActionModel { public int? Id { get; set; } public int State { get; set; } public string Prefix { get; set; } public string Index { get; set; } public int? ParentID { get; set; } } 解决方法
我99%肯定没有内置的实用程序方法。这不是一个很常见的任务,因为Web服务器通常不会使用URLEncoded键/值字符串进行响应。
你如何混合反射和LINQ?这工作: var foo = new EditListItemActionModel() { Id = 1,State = 26,Prefix = "f",Index = "oo",ParentID = null }; var properties = from p in foo.GetType().GetProperties() where p.GetValue(foo,null) != null select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(foo,null).ToString()); // queryString will be set to "Id=1&State=26&Prefix=f&Index=oo" string queryString = String.Join("&",properties.ToArray()); 更新: 要编写一个返回任何1深度对象的QueryString表示形式的方法,您可以这样做: public string GetQueryString(object obj) { var properties = from p in obj.GetType().GetProperties() where p.GetValue(obj,null) != null select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj,null).ToString()); return String.Join("&",properties.ToArray()); } // Usage: string queryString = GetQueryString(foo); 你也可以使它成为一个扩展方法,没有太多的额外工作 public static class ExtensionMethods { public static string GetQueryString(this object obj) { var properties = from p in obj.GetType().GetProperties() where p.GetValue(obj,null) != null select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj,null).ToString()); return String.Join("&",properties.ToArray()); } } // Usage: string queryString = foo.GetQueryString(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – WCF与Web-api平台中的数据和事务
- asp.net-mvc-4 – 为什么Razor HTML部分视图不能在’If’块
- asp.net-mvc – MVC4 RC WebApi参数绑定
- asp.net-core – 如何从控制器中解析ASP NET 5中的EF7当前数
- asp.net-mvc – 服务层是否可以访问HttpContext?
- asp.net-mvc – ASP.Net [HiddenInput]数据属性在Razor中用
- asp.net – 操作无法完成. FORMATETC结构无效
- asp.net – IQueryable和存储库 – 需要2?
- ASP.net MVC中的Ajax帮助器
- asp.net-mvc – RazorEngine:不能使用Html.Raw
推荐文章
站长推荐
- asp.net-mvc – ASP.NET MVC身份默认实现
- asp.net – SCRIPT5022:Sys.WebForms.PageReque
- asp.net – Grid.SelectedRow.Cells.Item(1).Tex
- MVC 3验证 – 仅在失去焦点或提交后显示错误消息
- asp.net-mvc – asp.net mvc – 视图中的命名空间
- 用于创建ASP.NET成员资格提供程序用户的脚本
- IE不保存asp.net身份验证令牌/ cookie
- asp.net-mvc – 用于Web.config的T4MVC
- asp.net – 将TemplateField的可见性绑定到Bound
- asp.net-mvc-3 – ASP.NET MVC 3和jQuery验证
热点阅读