前台调用后台函数

调用 var b = $ajax("WebApplication1._Default.GetDataSet", ["23"]);

js:/*方法全名,参数,类所在的程序集名称(当方法类所在的命名空间不是程序集名称时请传参数来)*/
function $ajax(paramMethod, paramValue, paramAssemblyName) {
    if (!paramMethod) { Dialog.alert("缺少全名称的方法参数", 1); }
    var result, params = "", assemblyName, className, methodName;
    if (paramValue) for (var i = 0; i < paramValue.length; i++) { params += "&param" + i + "=" + encodeURI(paramValue[i]); }; //获取参数
    className = paramMethod.substring(0, paramMethod.lastIndexOf(‘.‘));     // 获取方法所在类名称
    methodName = paramMethod.substring(paramMethod.lastIndexOf(‘.‘) + 1);   // 获取方法名称
    assemblyName = className.substring(0, className.lastIndexOf(‘.‘)); if (paramAssemblyName) assemblyName = paramAssemblyName; // 获取命名空间名称
    $.ajax({ url: "/../Ajax.ashx?Assembly=" + assemblyName + "&Class=" + className + "&Method=" + methodName + params, type: "POST", async: false,
        success: function (data) { result = eval("(" + data + ")"); },
        error: function (data) {
            layer.msg(data.responseText, 2, 0);
        }
    });
    return result;
}

Ajax.ashx:

using System; using System.Collections.Generic; using System.Web; using System.Web.SessionState; using System.Data; using System.Reflection; using System.IO; using System.Web.Script.Serialization;

namespace Chengrui.RSP.UILayer {     /// <summary>     /// Ajax 的摘要说明     /// </summary>     public class Ajax : IHttpHandler, IRequiresSessionState     {

#region public void GetMethod() 获取参数         /// <summary>         /// 获取参数         /// </summary>         /// <param name="context">界面内容</param>         /// <param name="paramField">参数</param>         /// <returns></returns>         public string GetRequest(HttpContext context, string paramField)         {             try { return context.Request[paramField] == null || context.Request[paramField].ToString() == "undefined" ? "" : context.Request[paramField].ToString().Trim(); }             catch { return string.Empty; }         }         #endregion

public void ProcessRequest(HttpContext context)         {             object result = null;             try             {                 string assemblyName = this.GetRequest(context, "Assembly"), className = this.GetRequest(context, "Class"), methodName = this.GetRequest(context, "Method");                                 //获取程序集                 Type type = null;                 try { Assembly myAssembly = Assembly.Load(assemblyName); type = myAssembly.GetType(className); }                 catch { type = Assembly.GetExecutingAssembly().GetType(className); }

//找不到程序集,就遍历基目录下的所有以Chengrui.RS.命名的程序集,而获取方法                 if (type == null)                 {                     FileInfo[] arrFileInfo = new DirectoryInfo(AppDomain.CurrentDomain.RelativeSearchPath).GetFiles("Chengrui.RS.*.dll");                     foreach (FileInfo myFile in arrFileInfo) { type = Assembly.Load(myFile.Name.Substring(0, myFile.Name.LastIndexOf(‘.‘))).GetType(className); if (type != null) break; }                 }

if (type != null)                 {                     System.Reflection.MethodInfo methodInfo = type.GetMethod(methodName);                     if (methodInfo != null)//判断操作页面是否有该方法                     {                         object[] args = new object[methodInfo.GetParameters().Length];                         //对方法名的参数进行赋值                         for (int i = 0; i < methodInfo.GetParameters().Length; i++) { args[i] = Convert.ChangeType(this.GetRequest(context, "param" + i.ToString()), methodInfo.GetParameters()[i].ParameterType); }                         //执行方法                         result = methodInfo.Invoke(Activator.CreateInstance(type), args);                     }                     else                         result = "没有找到【assemblyName:" + assemblyName + "】.【className:" + className + "】.【methodName:" + methodName + "】方法";                 }                 else                     result = "没有找到【assemblyName:" + assemblyName + "】.【className:" + className + "】类";             }             catch (Exception myEx) { result = myEx.Message; }            // context.Response.Write(CommonMethod.ToJson(result));             context.Response.Write(ToJson(result));         }

public bool IsReusable         {             get             {                 return false;             }         }

#region public static string ToJson(object obj)         /// <summary>         /// 转Json         /// </summary>         /// <param name="obj"></param>         /// <returns></returns>         public static string ToJson(object obj)         {             if (obj == null) obj = string.Empty;             JavaScriptSerializer myJson = new JavaScriptSerializer();             if (obj.GetType().Name == "DataTable")             {                 DataTable myDt = (DataTable)obj;                 string tableName = myDt.TableName == "" ? "TableName1" : myDt.TableName;                 Dictionary<string, object> dic = new Dictionary<string, object>();                 dic.Add(tableName, RowsToDictionary(myDt));                 return myJson.Serialize(dic);             }             else if (obj.GetType().Name == "DataSet")             {                 DataSet myDs = (DataSet)obj;                 Dictionary<string, object> dic = new Dictionary<string, object>();                 for (int i = 0; i < myDs.Tables.Count; i++)                 {                     string tableName = myDs.Tables[i].TableName == "" ? "TableName" + i.ToString() : myDs.Tables[i].TableName;                     dic.Add(tableName, RowsToDictionary(myDs.Tables[i]));                 }                 return myJson.Serialize(dic);             }             else                 return myJson.Serialize(obj);         }

private static List<Dictionary<string, object>> RowsToDictionary(DataTable table)         {             List<Dictionary<string, object>> objs = new List<Dictionary<string, object>>();             foreach (DataRow dr in table.Rows)             {                 Dictionary<string, object> drow = new Dictionary<string, object>();                 for (int i = 0; i < table.Columns.Count; i++)                 {                     drow.Add(table.Columns[i].ColumnName, dr[i]);                 }                 objs.Add(drow);             }             return objs;         }

#endregion     } }

前台调用后台函数

时间: 2024-10-12 03:19:16

前台调用后台函数的相关文章

.net使用Ajax在前台调用后台方法

/*--------前台JS代码-----------*/ var http_request; function GetAjaxObject(coaInfo) { //根据浏览器的不同来获取XMLHttpRequest对象 if (window.XMLHttpRequest) { // Mozilla, Safari, ... http_request = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE http_re

JS 之 前台调用后台变量和方法

      在我们平时的网站开发过程中,并不是所有的网页都是后台查询出一个DataTable或者List然后绑定到DataGrid上.我们可能还会遇到前台需要后台的某一个变量,或者前台某个显示的地方需要调用一下后台的某一个查询的方法.下面我就给大家列举一个小例子: Asp.Net前台代码: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta ht

LigerUi-js中ajax前台调用后台Json格式转换!(已解决)

LigerUi-js中ajax前台调用后台Json格式转换!(已解决) success: function (data, status) { var aaa = JSON2.stringify(data); alert(aaa ); } LigerUi-js中ajax前台调用后台Json格式转换!(已解决),布布扣,bubuko.com

前台调用后台事件和方法实现小结

在实际开发过程中,我们的HTML元素需要调用后台,而且需要让后台进行复杂运算后再进行数据重新绑定操作,遇到这样的问题怎么办呢?可能有人说在后台创建一个方法,该方法实现绑定数据操作,但是实际呢?结果不尽人意,它没有执行绑定的实现,而只是简单的执行一下方法但是前台无反应,为什么出现这样的情况?原来前台调用后台方法其实只是返回结果,对实现过程及元素组合变化不管不问,它只是关注执行后的结果,不为过程买单,那么有什么方法解决这个问题呢?想想?我们可不可以让前台HTML元素触发ASP.NET按钮来触发事件呢

前台JavaScript根据回车和控件ID调用后台函数

1.程序中的js代码. document.onkeydown =function () { if (event.keyCode == 13 && document.getElementById('lnkRechercher')) { document.getElementById("lnkRechercher").click(); } } 2.document.onkeydown比较好, 如果event="onKeyDown"和for="d

Asp.Net前台调用后台变量

1.Asp.Net中几种相似的标记符号: < %=...%>< %#... %>< % %>< %@ %>解释及用法 答: < %#... %>: 是在绑定控件DataBind()方法执行时被执行,用于数据绑定 如: < %# Container.DataItem("tit") %> < %= %>: 在程序执行时被调用,可以显示后台变量值 如: *.aspx中: < %= aaa %> *

.net 使用$.ajax实现从前台调用后台方法

/*---------------前台*-----------------/$(function() { $("#btnOK").click(function() { $.ajax({ type: "Post", url: "demo.aspx/GetStr", //方法传参的写法一定要对,str为形参的名字,str2为第二个形参的名字 data: "{'str':'I am','str2':'XXX'}", contentT

asp.net中&lt;input type=button&gt;无法调用后台函数

例如:用<input id="bt1" type="button" runat="server" Onclick="btnLogin_Click"/>添加一个按钮(注:不是从工具箱拖进去的控件)在default.aspx.cs中有个btnLogin_Click()方法,但是按钮bt1无法实现delete功能. 解决方案:把onclick改成OnServerClick. onclick,onclientclick和o

NC前台调用后台接口方法

1 import nc.bs.framework.common.NCLocator; 2 3 AggQcFormbatchVO []aggvos = NCLocator.getInstance().lookup(IQc_formbatchMaintain.class).update(new AggQcFormbatchVO[] { aggvo },new AggQcFormbatchVO[] { aggvo }); 原文地址:https://www.cnblogs.com/xaopohi-WXF