• asp.net ajax 环境 c#与js互调


     1.JS和.Net前后臺互相調用總結
    HTML code

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="JavaScript get Net Function.aspx.cs" Inherits="JavaScript_get_Net_Function" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>前臺與后臺方法護調總結</title>
    <%--
    JavaScript異步調用定義在ASP.Net頁面中的方法, 我們需要:
    1.將該方法聲明為公有(public);
    2.將該方法聲明為類方法(C#中的static,VB.NET中的Shared),而不是實例方法;
    3.將該方法添加【WebMethod】屬性
    4.將頁面中ScriptManager控件的EnablePageMethods屬性設置為true;
    5.在客戶端使用如下JavaScript語法調用該頁面方法
    PageMethods.[MethodName](param1,param2,...,callbackFunction);
    6.為客戶端異步調用指定回調函數,在回調函數中接受返回值并進一步處理;
    7.添加 using System.Web.Services;
    --%>

    <%--
    ASP.Net后臺調用JavaScript function的方法,我們要注意:
    1.盡量少用Response.Write(<script></script>);這種方法,它會影響CSS導致頁面效果偏差
    2.C#中使用ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "JS('"+param1+"','"+param2+"')", true);
    3.添加 using System.Web.UI;
    --%>

    <script type="text/javascript">

    /*-------------JavaScript調用.Net后臺Start----------------------------------*/
    function JsCallCSharp(param1)
    {
    PageMethods.SayHelloFromPage(param1,onSayHelloSucceeded);
    }

    function onSayHelloSucceeded(result)
    {
    alert(result);
    }
    /*-------------JavaScript調用.Net后臺End----------------------------------*/

    /*-------------.Net調用JavaScript Start-----------------------------------*/
    function CSharpCallJs(param1,param2)
    {
    alert(param1
    + param2);
    }
    /*-------------.Net調用JavaScript Start-----------------------------------*/
    </script>

    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server" />
    </div>

    <asp:Button ID="Button1" onclick="Button1_Click" OnClientClick="JsCallCSharp('takako');" runat="server" Text="Button1" />

    </form>
    </body>
    </html>

    C# code

    using System;
    using System.Web.Services;
    using System.Web.UI;

    public partial class JavaScript_get_Net_Function : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
    string param1 = "你好:";
    string param2 = "takako_mu";
    ScriptManager.RegisterStartupScript(
    this, this.GetType(), "edit", "CSharpCallJs('" + param1 + "','" + param2 + "');", true);
    }

    [WebMethod]
    public static string SayHelloFromPage(string name)
    {
    return string.Format("Hello {0}!", name);
    }
    }



    2.Js調用WebService總結
    JScript code

    /*--相當于GridViewBind()-------------------------------------------------------------------------------------------*/ 
        function Search(pagesize,pageCurrentCount)
        {
            var UserName=$get("optSelectUserName").value;
            var Project=$get("optSelectProject").value;
            GetData(pagesize,pageCurrentCount,UserName,Project);
            return false;
        }
    
        function GetData(pagesize,pageCurrentCount,userName, project)
        {
            $get("displayImage").style.display="block";
            var UserName=userName;
            var Project=project;
            WebService_AJAXGridView.GetData(pagesize,pageCurrentCount,UserName, Project, SucceededCallback, FailedCallback,"XmlDocument");
        }
        
        function SucceededCallback(result, userContext, methodName)
        {
            if (userContext == "XmlDocument")
            {
                   UpdateTable(result);
            }
            $get("displayImage").style.display="none";
            //document.getElementById("lab_TotalPage").innerText=
        }
    
        function FailedCallback(error)
        {
            // Display the error.    
            var stackTrace=error.get_stackTrace();
            var message= error.get_message();
            var statusCode=error.get_statusCode();
            var exceptionType=error.get_exceptionType();
            var timeout=error.get_timedOut();
            
            var errstr="推疊追蹤: "+ stackTrace+"\n";
            errstr+="服務錯誤:"+ message+"\n";
            errstr+="狀態碼:"+ statusCode+"\n";
            errstr+="例外類型:"+ exceptionType+"\n";
            errstr+="逾時:"+ timeout+"\n";
            errstr+="請關掉IE, 重新進入 !!";
            alert(errstr);
    
            $get("displayImage").style.display="none";
        }
    /*--相當于GridViewBind()-------------------------------------------------------------------------------------------*/    
    
    


    C# code

    //WebService
    
    using System;
    using System.Data;
    using System.Xml;
    using System.Text;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Web.Script.Services;
    using System.Web.Script.Serialization;
    using System.Web.Security;
    using System.Xml.Linq;
    using System.Data.Sql;
    using System.Data.SqlClient;
    
     
    
    /// <summary>
    /// WebService_AJAXGridView 的摘要描述
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // 若要允許使用 ASP.NET AJAX 從指令碼呼叫此 Web 服務,請取消註解下一行。
     [System.Web.Script.Services.ScriptService]
    public class WebService_AJAXGridView : System.Web.Services.WebService {
    
        public WebService_AJAXGridView () {
    
            //如果使用設計的元件,請取消註解下行程式碼 
            //InitializeComponent(); 
        }
    
        //Create By Takako_Yang,at 2008/12/04
        [WebMethod(Description = "My AJAX Gridview Data Select", EnableSession = true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
        public XmlDocument GetData(int pagesize,int pageCurrentCount,string userName, string project)
        {
            DailyWorkFactory myDailyWorkFactory = new DailyWorkFactory();
            DataTable dt = myDailyWorkFactory.GetDailyWork(0, 1,pagesize,pageCurrentCount, userName, project, "");//flag1用來判斷Select來源自現有的,還是編輯時Create的新的
            StringBuilder sb = new StringBuilder();
            sb.Append("<AJAXSet>");
            //select [No],Project,Item,Code,[Description (purpose/value)],
            //Status,[%],[Start Date],[Due Date],Owner,[Day/Hour] from daily_work
            foreach (DataRow myDataRow in dt.Rows)
            {
                string No = myDataRow[0].ToString();
                string Project1 = myDataRow[1].ToString();
                string Item = myDataRow[2].ToString();
                string Code = myDataRow[3].ToString();
                string Desciption = myDataRow[4].ToString();
                string Status = myDataRow[5].ToString();
                string Percent = myDataRow[6].ToString();
                string StartDate = (Convert.ToDateTime(myDataRow[7])).ToString("yyyy/MM/dd");
                string DueDate = (Convert.ToDateTime(myDataRow[8])).ToString("yyyy/MM/dd");
                string Owner = myDataRow[9].ToString();
                string NeedTime = myDataRow[10].ToString();
                sb.Append("<AJAXData>");
                sb.Append("<P1>").Append(No).Append("</P1>");
                sb.Append("<P2>").Append(Project1).Append("</P2>");
                sb.Append("<P3>").Append(Item).Append("</P3>");
                sb.Append("<P4>").Append(Code).Append("</P4>");
                sb.Append("<P5>").Append(Desciption).Append("</P5>");
                sb.Append("<P6>").Append(Status).Append("</P6>");
                sb.Append("<P7>").Append(Percent).Append("</P7>");
                sb.Append("<P8>").Append(StartDate).Append("</P8>");
                sb.Append("<P9>").Append(DueDate).Append("</P9>");
                sb.Append("<P10>").Append(Owner).Append("</P10>");
                sb.Append("<P11>").Append(NeedTime).Append("</P11>");
                sb.Append("</AJAXData>");
            }
            sb.Append("</AJAXSet>");
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(sb.ToString());
            return xmlDoc;
        }
    
  • 相关阅读:
    SpringBoot集成Swagger2并配置多个包路径扫描
    SpringBoot基于EasyExcel解析Excel实现文件导出导入、读取写入
    SpringBoot + SpringSecurity + Quartz + Layui实现系统权限控制和定时任务
    Redis数据持久化(RDB、AOF)
    so安全编译选项(栈溢出保护)
    Python调用Chrome下载文件
    AtomicInteger如何保证线程安全以及乐观锁/悲观锁的概念
    SpringCloud:Eureka的健康检测机制
    共享锁(S锁)和排它锁(X锁)
    Collection接口及其常用子类(java.util包)
  • 原文地址:https://www.cnblogs.com/sishahu/p/2182037.html
Copyright © 2020-2023  润新知