读书人

ajax中怎么将Request得到的NameValueC

发布时间: 2012-04-19 14:36:43 作者: rapoo

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

读书人网 >asp.net

热点推荐