AJAX下客戶端調用服務端頁面方法

1.客戶端代碼如下:

 

//函數功能:客戶端調用頁面服務端方法

//示例:

//參數說明:

//isStaticMethod:是否是靜態方法

//methodName:方法名稱

//methodParamter:[可選]方法參數,必須是類型MethodParamter的實例或者null值(無參數)
//
callBackMethod:[可選]方法調用完後回調的客戶端方法,客戶端方法形式爲 function callBackMethod(result){},result是個json對象,例如:function HandleCheckListResult(result){},參數值就是'HandleCheckListResult'
//
assemblyAndClassName:[可選]頁面服務端所在組件和類名,形式爲: 'AssemblyName|ClassFullName',例如: Weiky.dll|Weiky.AccessoriesForm'
function CallPageMethod(isStaticMethod,methodName,methodParamter,callBackMethod,assemblyAndClassName)
{
    
if(methodParamter && typeof(methodParamter.AddBoolParamter) != 'function')
    
{
        alert(“
參數methodParamter必須是類型MethodParamter的實例或者null值");
        
return;
    }

    
if(assemblyAndClassName == null)
    
{
        
if(typeof(AssemblyAndClassName) != 'undefined')
        
{
            assemblyAndClassName 
= AssemblyAndClassName;
        }

        
else
        
{
            alert(
"未提供頁面服務端所在組件和類名");
            
return;
        }

    }

    
try
    
{
        MyWebService.CallPageMethod(assemblyAndClassName,isStaticMethod,methodName,methodParamter
?methodParamter.ToJson():null,methodParamter.ToType(),callBackMethod?callBackMethod:'', CallBackByWebService,HandleServiceMethodCallError);                                        
    }

    
catch(err)
    
{
        alert(
'將參數轉換成JSON對象失敗!');
    }

}


function CallBackByWebService(result)
{
    
var json = ConvertStringToJson(result);
    
if(json.Type != 0)
    
{
        ShowMessageBox2(json);
    }

    
else
    
{
        
var callBackMethod = json.HighlevelMessage;
        
if(callBackMethod != '')
        
{
            json.HighlevelMessage 
= '';
            json.Message 
= ReplaceString(json.Message,'',' ');
            eval(callBackMethod 
+ '(json)');
        }

    }

}


function MethodParamter()
{
    
var paramter = '';
    
var json = null;
    
    
this.AddStringParamter = function (value)
    
{
        AddParamter(
'string',ReplaceString(ReplaceString(value,'"','/"'),' ',''));
    }

    
    
this.AddGuidParamter = function (value)
    
{
        AddParamter(
'guid',value);
    }

    
    
this.AddDateParamter = function (value)
    
{
        AddParamter(
'date',value);
    }

    
    
this.AddIntParamter = function (value)
    
{
        AddParamter(
'int',value);
    }

    
    
this.AddDecimalParamter = function (value)
    
{
        AddParamter(
'decimal',value);
    }

    
    
this.AddBoolParamter = function (value)
    
{
        AddParamter(
'bool',value);
    }

    
    
function AddParamter(type,value)
    
{
        
if(paramter != '')
        
{
            paramter 
+= ','
        }

        paramter 
+= '{"Type":"' + type + '","Value":"' + value + '"}';
    }

    
    
this.AddJsonParamter = function (p)
    
{
        json 
= p;
    }

    
    
this.ToJson = function ()
    
{
        
if(json)
        
{
            
return json;
        }

        
if(paramter != '')
        
{
            
return eval('[' + paramter + ']');
        }

        
        
return null;
    }

    
    
this.ToType = function ()
    
{
        
return json?1:0;
    }

}

2.服務端webservice提供給ScriptManager控件,webservice代碼如下:

 

[System.Web.Script.Services.ScriptService]
    [WebService(Namespace 
= "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo 
= WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(
false)]
    
public class MyWebService : System.Web.Services.WebService
    
{
[WebMethod(EnableSession 
= true)]
        
public string CallPageMethod(string assemblyAndClassName, bool isStaticMethod, string methodName, object paramtersPackage,int mpType,string callBackMethod)
        
{
            
try
            
{
                
object result = "";
                
bool succeed = false;
                
if (isStaticMethod)
                
{
                    Type type 
= GetActualType(assemblyAndClassName);
                    
if (type != null)
                    
{
                        succeed 
= true;
                        
if (mpType == 1)
                        
{
                            result 
= type.InvokeMember(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static, nullnullnew object[] { paramtersPackage });
                        }

                        
else
                        
{
                            result 
= type.InvokeMember(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static, nullnull, GetMethodArgs(paramtersPackage));
                        }

                    }

                }

                
else
                
{
                    
object o = WebBase.GetActualInstance(assemblyAndClassName, this.Server.MapPath("~/bin/"));
                    
if (o != null)
                    
{
                        succeed 
= true;
                        
if (mpType == 1)
                        
{
                            result 
= o.GetType().InvokeMember(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Instance, null, o, new object[] { paramtersPackage });
                        }

                        
else
                        
{
                            result 
= o.GetType().InvokeMember(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Instance, null, o, GetMethodArgs(paramtersPackage));
                        }

                    }

                }


                
return succeed ? 0 : 1, succeed ? (result == null ? "" : result.ToString()) : string.Format("獲取組件信息失敗,請檢查組件參數{0}是否正確", assemblyAndClassName);
            }

            
catch (Exception err)
            
{
                
return err.Message;
            }

        }

private object[] GetMethodArgs(object paramtersPackage)
        
{
            
if (paramtersPackage == nullreturn null;

            
int i = 0;
            
object[] args = new object[((object[])paramtersPackage).Length];
            
foreach (System.Collections.Generic.Dictionary<stringobject> p in (object[])paramtersPackage)
            
{
                
switch (p["Type"].ToString().ToLower())
                
{
                    
case "string":
                        args[i
++= p["Value"].ToString().Replace(""," ");
                        
break;
                    
case "guid":
                        args[i
++= new Guid(p["Value"].ToString());
                        
break;
                    
case "date":
                        args[i
++= Convert.ToDateTime(p["Value"].ToString());
                        
break;
                    
case "int":
                        args[i
++= Convert.ToInt32(p["Value"].ToString());
                        
break;
                    
case "decimal":
                        args[i
++= Convert.ToDecimal(p["Value"].ToString());
                        
break;
                    
case "bool":
                        args[i
++= Convert.ToBoolean(p["Value"].ToString());
                        
break;
                    
default:
                        args[i
++= p["Value"];
                        
break;
                }

            }

            
return args;
        }

 
private WebBaseForm GetActualInstanceForm(string assemblyAndClassName)
        
{
            
object o = WebBase.GetActualInstance(assemblyAndClassName,this.Server.MapPath("~/bin/"));
            
if (o != null)
            
{
                
if (o is WebBaseForm)
                
{
                    
return (WebBaseForm)o;
                }

            }


            
return null;
        }


        
private Type GetActualType(string assemblyAndClassName)
        
{
            
if (assemblyAndClassName != "")
            
{
                
string[] ac = assemblyAndClassName.Replace("!""/").Split('|');
                
if (ac.Length == 2)
                
{
                    ac[
0= WebBase.AddPath(ac[0],this.Server.MapPath("~/bin/"));
                    
return System.Reflection.Assembly.LoadFrom(ac[0]).GetType(ac[1]);
                }

            }


            
return null;
        }

}

 3.客戶端調用示例:

 

function DataDDL_Change(ddl)
        
{
            
var mp = new MethodParamter();
            mp.AddIntParamter(DropDownList_GetValue(ddl));
            mp.AddIntParamter(EntityObjectId);
            CallPageMethod(
true,'GetEntityData',mp,'LoadDataTree');
        }

        
        
function LoadDataTree(json)
        
{
alert(json.Message);
}

總結:通過這樣的封裝,客戶端調用服務端靜態/實例方法非常方便,並且不會引起任何頁面的postback。上面所用客戶端技術有ajax,json等
發佈了45 篇原創文章 · 獲贊 29 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章