日期:2014-05-18  浏览次数:20485 次

ajax中如何将Request得到的NameValueCollection转换成实体类
实体类如下:

  public class Peson
  {
  public string Name { get; set; }
  public string Sex { get; set; }
  }

前台通过Jquery的中post或get方法发送数据到后台,格式:{"Name":"张三","Sex":"男"} 

后台通过Request获取数据并添加到NameValueCollection中;
NameValueCollection paramValueCollection = new NameValueCollection();
paramValueCollection.Add(context.Request.QueryString);
paramValueCollection.Add(context.Request.Form);

如何将NameValueCollection转换成实体类

------解决方案--------------------
C# code

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Type type = Type.GetType("WebApplication1.Peson");
            object obj = null;
            Type List = typeof(List<>);
            List = List.MakeGenericType(type);
            MethodInfo ListAdd = List.GetMethod("Add");
            object listObj = Activator.CreateInstance(List);
            for (int i = 0; i < Request.QueryString.Count; i++)
            {
                obj = Activator.CreateInstance(type);
                type.GetProperty("Key").SetValue(obj, Request.QueryString.GetKey(i), null);
                type.GetProperty("Value").SetValue(obj, Request.QueryString[i], null);
                ListAdd.Invoke(listObj, new object[] { obj });
            }
            int Count = (int)List.GetProperty("Count").GetValue(listObj, null);
            for (int i = 0; i < Count; i++)
            {
                obj = List.InvokeMember("Item", BindingFlags.GetProperty, null, listObj, new object[] { i });
                foreach (PropertyInfo p in type.GetProperties())
                    Response.Write(p.GetValue(obj, null) + "<br/>");
            }
        }
    }
    public class Peson
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }
}