WebForm快速处理Ajax

翅膀的初衷

发表于2013-08-03 22:48:36

  用Asp.net MVC感受最深的一点就是写Ajax方法真方便,不需要写什么Request.Form与Request.QueryString,直接定义好形参,系统什么都处理好了,哪怕是一个自定义的实体,都帮你弄得妥妥的,任何对象直接 return Json(obj);,方便快捷!

  不过呢,有时我们却还是不得不继续与WebForm,.net2.0,vs2005之类的关键词打交道,其实要想在.net 2.0的WebForm中实现类似功能,只要一个小小的处理类就可以了.

  核心代码:

   /***********************************************
   * Ajax处理类
   * 作者:翅膀的初衷
   * 网址:http://www.jiniannet.com
   ************************************************/
   public class AjaxParser
    {
        private object classObject;

        public AjaxParser(object obj)
        {
            classObject = obj;//Void
        }

        public void ExcuteJson(string action, HttpContext context)
        {
            context.Response.ContentType = "application/json";
            NameValueCollection collection;
            switch (context.Request.HttpMethod.Trim().ToUpper())
            {
                case "GET":
                    collection = context.Request.QueryString;
                    //parm = 
                    break;
                case "POST":
                    collection = context.Request.Form;
                    break;
                default:
                    collection = new NameValueCollection();
                    for (int i = 0; i < context.Request.Form.Count; i++)
                    {
                        collection[context.Request.Form.GetKey(i)] = context.Request.Form[i];
                    }
                    for (int i = 0; i < context.Request.QueryString.Count; i++)
                    {
                        collection[context.Request.QueryString.GetKey(i)] = context.Request.QueryString[i];
                    }
                    break;
            }

            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(ExcuteMethod(action,collection)));
            context.Response.End();
        }

        public object ExcuteMethod(string action,  NameValueCollection collection)
        {

            Type type = classObject.GetType();
            MethodInfo m = GetMethod(action,type);
            if (m != null)
            {
                object[] parm = GetValue(m.GetParameters(), collection);
                return m.Invoke(classObject, parm);
            }
            return null;
        }

        private object[] GetValue(ParameterInfo[] info, NameValueCollection collection)
        {
            object[] value = new object[info.Length];
            for (int i = 0; i < info.Length; i++)
            {

                if (info[i].ParameterType.FullName.StartsWith("System."))
                {
                    object val = collection[info[i].Name];
                    if (val != null)
                    {
                        value[i] = Convert.ChangeType(val, info[i].ParameterType);
                    }
                    else
                    {
                        value[i] = info[i].DefaultValue;
                    }

                }
                else
                {
                    Type t = info[i].ParameterType;
                    value[i] = PopulateEntity(t, collection);
                }
            }

            return value;
        }

        public MethodInfo GetMethod(string name, Type t)
        {
            MethodInfo[] list = t.GetMethods(BindingFlags.Public | BindingFlags.Instance);

            foreach (MethodInfo m in list)
            {
                if (m.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    return m;
                }
            }
            return null;
        }

        public object PopulateEntity(Type type, System.Collections.Specialized.NameValueCollection collection)
        {
            object entity = Activator.CreateInstance(type);
            PropertyInfo[] propertys = type.GetProperties();
            foreach (PropertyInfo item in propertys)
            {
                if (canChange(item.PropertyType.FullName) && collection[item.Name] != null)
                {
                    if (item.PropertyType.IsValueType && string.IsNullOrEmpty(collection[item.Name]))
                    {
                    }
                    else
                    {
                        item.SetValue(entity, Convert.ChangeType(collection[item.Name], item.PropertyType), null);
                    }
                }
            }
            return entity;
        }

        private bool canChange(string fullName)
        {
            switch (fullName)
            {
                case "System.String":
                case "System.Byte":
                case "System.Boolean":
                case "System.DateTime":
                case "System.Decimal":
                case "System.Double":
                case "System.Guid":
                case "System.Int16":
                case "System.Int32":
                case "System.Int64":
                case "System.SByte":
                case "System.Single":
                case "System.UInt16":
                case "System.UInt32":
                case "System.UInt64":
                case "System.Object":
                    return true;
                default:
                    return false;
            }
        }

  然后新建一个Ajax.aspx,将页面中的除第一行外的所有HTML都清除:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Ajax.aspx.cs" Inherits="JinianNet.SiteNavigation.Web.admin.Ajax" %>

  后台代码:

    public partial class Ajax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();
            if (!string.IsNullOrEmpty(Request.QueryString["action"]))
            {
                AjaxParser ap = new AjaxParser(this);
                ap.ExcuteJson(Request.QueryString["action"], this.Context);
            }
        }

  //示例方法
        public Hashtable CategoryAdd(Product model)
        {
            Hashtable hash = new Hashtable();
            model.CreateTime = DateTime.Now;
            if(new ProductDAL.Insert(model))
            {
                hash["success"] = true;
                hash["msg"] = "操作成功";
            }
            else
            {
                hash["success"] = false;
                hash["msg"] = "执行失败,请重试";
            }
            return hash;
        }

  //下面可以任意思添加方法
    }

  Ajax调用示例:

$.ajax({
    url:"ajax.aspx?action=add",
    data:"id=1&name=某产品&price=80",
    success:function(json){
        if(json.success){
            alert('添加成功');
        }else{
            alert(json.msg);
        }
    }
})