ASP.Net:发送一个Ajax请求 [英] ASP.Net: Sending an Ajax Request

查看:162
本文介绍了ASP.Net:发送一个Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我很难找到有关如何从一个ASP.Net控件发送Ajax请求以从服务器更新到另一个控件的良好解释或教程.

UpdatePanel是唯一的解决方案,它真的避免了回发吗?

Hi,

I''m having difficulty finding a good explanation or tutorial on how to send an Ajax request from one ASP.Net control to update from the server to another control.

Is UpdatePanel is the only solution and does it really avoid a postback?

Any help with this is greatly appreciated.

推荐答案

在大多数情况下,UpdatePanel 是一个不错的选择,它易于使用并节省了大量的部分内容,页面渲染脚本生成时间.还有其他方法.

1.您可以实现 ICallbackEventHandler

In most of the case UpdatePanel is a good choice, it is easy to use and saves your lot of partial-page rendering script generation time.yet there are alternate ways.

1. You may implement the ICallbackEventHandler

public partial class CallBack_DB_aspx :
    System.Web.UI.Page, System.Web.UI.ICallbackEventHandler


客户端事件触发对服务器的回调,该回调将结果作为字符串返回.然后必须编写客户端显示逻辑.


Aspx页面


A client side event triggers a callback to server which will return the result as string. you have to write client side display logic then.


Aspx page

<%@ Page Language="C#" AutoEventWireup="true"

  CodeFile="ClientCallback.aspx.cs" Inherits="ClientCallback" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML

  1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
  <title>Client Callback Example</title>
  <script type="text/ecmascript">
    function LookUpStock()
    {
        var lb = document.getElementById("ListBox1");
        var product = lb.options[lb.selectedIndex].text;
        CallServer(product, "");
    }

    function ReceiveServerData(rValue)
    {
        document.getElementById("ResultsSpan").innerHTML = rValue;

    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
    <div>
      <asp:ListBox ID="ListBox1" Runat="server"></asp:ListBox>
      <br />
      <br />
      <button type="Button" onclick="LookUpStock()">Look Up Stock</button>
      <br />
      <br />
      Items in stock: <span id="ResultsSpan" runat="server"></span>
      <br />
    </div>
  </form>
</body>
</html>



后台代码



Code-behind

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ClientCallback : System.Web.UI.Page,
     System.Web.UI.ICallbackEventHandler
{
    protected System.Collections.Specialized.ListDictionary catalog;
    protected String returnValue;
    protected void Page_Load(object sender, EventArgs e)
    {
        String cbReference =
            Page.ClientScript.GetCallbackEventReference(this,
            "arg", "ReceiveServerData", "context");
        String callbackScript;
        callbackScript = "function CallServer(arg, context)" +
            "{ " + cbReference + ";}";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
            "CallServer", callbackScript, true);

        catalog = new System.Collections.Specialized.ListDictionary();
        catalog.Add("monitor", 12);
        catalog.Add("laptop", 10);
        catalog.Add("keyboard", 23);
        catalog.Add("mouse", 17);

        ListBox1.DataSource = catalog;
        ListBox1.DataTextField = "key";
        ListBox1.DataBind();

    }

    public void RaiseCallbackEvent(String eventArgument)
    {
        if (catalog[eventArgument] == null)
        {
            returnValue = "-1";
        }
        else
        {
            returnValue = catalog[eventArgument].ToString();
        }
    }
    public String GetCallbackResult()
    {
        return returnValue;
    }
}





2.使用网络服务方法

.NET Framework使您可以使用客户端脚本从浏览器异步调用ASP.NET Web服务(.asmx)方法.该页面可以调用基于服务器的方法而无需回发,也无需刷新整个页面,因为在浏览器和服务器之间仅传输数据.

ASPX文件





2. Using web service method

The .NET Framework enables you to call ASP.NET Web services (.asmx) methods from the browser asynchronously by using client script. The page can call server-based methods without a postback and without refreshing the whole page, because only data is transferred between the browser and the server.

ASPX file

<%@ Page Language="C#" %>

<!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 id="Head1" runat="server">
        <style type="text/css">
            body {  font: 11pt Trebuchet MS;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }

            .text { font: 8pt Trebuchet MS }
        </style>

        <title>Simple Web Service</title>

            <script type="text/javascript">

            // This function calls the Web Service method.
            function GetServerTime()
            {
                Samples.AspNet.ServerTime.GetServerTime(OnSucceeded);
            }

            // This is the callback function that
            // processes the Web Service return value.
            function OnSucceeded(result)
            {
                var RsltElem = document.getElementById("Results");
                RsltElem.innerHTML = result;
            }

        </script>

    </head>

    <body>
        <form id="Form1" runat="server">
         <asp:ScriptManager runat="server" ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="ServerTime.asmx" />
                </Services>
            </asp:ScriptManager>
            <div>
                <h2>Server Time</h2>
                    <p>Calling a service that returns the current server time.</p>

                    <input id="EchoButton" type="button"

                        value="GetTime" onclick="GetServerTime()" />
            </div>
        </form>

        <hr/>

        <div>
            <span id="Results"></span>
        </div>

    </body>

</html>




Web服务-代码隐藏




web service - Code-behind

<%@ WebService Language="C#" Class="Samples.AspNet.ServerTime" %>


using System;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

namespace Samples.AspNet
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class ServerTime : System.Web.Services.WebService
    {

        [WebMethod]
        public string GetServerTime()
        {
            return String.Format("The server time is {0}.",
                DateTime.Now);

        }

    }

}




3.下层客户端回叫

前面的示例演示如何通过调用自动为Web服务生成的代理类从客户端脚本调用Web服务.您还可以从客户端脚本对Web服务进行较低级别的调用.如果必须管理通信层或检查从服务器发送或从服务器发送的数据,则可以执行此操作.要以这种方式调用Web服务,请使用WebRequest类.

下面的示例演示如何使用WebRequest对象来实现连接到指定URL(HTTP端点)的GET和POST Web请求.




3. Lower - Level Client Callback

The previous example shows how to call Web services from client script by calling the automatically generated proxy classes for the Web service. You can also make lower-level calls to Web services from client script. You might do this if you have to manage the communication layer or examine the data that is being sent to or from the server. To call Web services in this manner, you use the WebRequest class.

The following example shows how to use a WebRequest object to implement GET and POST Web requests that connect to the specified URLs (HTTP end points).

// ConnectingEndPoints.js

var resultElement;

function pageLoad()
{
    resultElement =


get(" ); } // 此函数执行GET Web请求. 函数GetWebRequest() { alert(" ); // 实例化WebRequest. var wRequest = Sys.Net.WebRequest(); // 设置请求URL. wRequest.set_url(" ); alert(" ); // 设置请求动词. wRequest.set_httpVerb(" ); // 设置请求回调函数. wRequest.add_completed(OnWebRequestCompleted); // 清除结果区域. resultElement.innerHTML = " ; // 执行请求. wRequest.invoke(); } // 此函数执行POST Web请求. 函数PostWebRequest() { alert(" ); // 实例化WebRequest. var wRequest = Sys.Net.WebRequest(); // 设置请求URL. wRequest.set_url(" ); alert(" ); // 设置请求动词. wRequest.set_httpVerb(" ); // 设置请求处理程序. wRequest.add_completed(OnWebRequestCompleted); // 设置POST的正文. var requestBody = " ; wRequest.set_body(requestBody); wRequest.get_headers()[" ] = requestBody.length; // 清除结果区域. resultElement.innerHTML = " ; // 执行请求. wRequest.invoke(); } // 此回调函数处理 // 请求返回值.称为异步 当前执行者// . 函数OnWebRequestCompleted(executor,eventArgs) { 如果(executor.get_responseAvailable()) { // 清除先前的结果. resultElement.innerHTML = " ; // 显示Web请求状态. resultElement.innerHTML + = " + executor.get_statusCode()+ " + executor.get_statusText()+ " + " < br/>"; // 显示Web请求标头. resultElement.innerHTML + = " ; resultElement.innerHTML + = executor.getAllResponseHeaders()+ " ; // 显示Web请求正文. resultElement.innerHTML + = " ; 如果(document.all) resultElement.innerText + = executor.get_responseData(); 其他 resultElement.textContent + = executor.get_responseData(); } } 如果( typeof (Sys)!== " undefined")Sys.Application.notifyScriptLoaded();
get("ResultId"); } // This function performs a GET Web request. function GetWebRequest() { alert("Performing Get Web request."); // Instantiate a WebRequest. var wRequest = new Sys.Net.WebRequest(); // Set the request URL. wRequest.set_url("getTarget.htm"); alert("Target Url: getTarget.htm"); // Set the request verb. wRequest.set_httpVerb("GET"); // Set the request callback function. wRequest.add_completed(OnWebRequestCompleted); // Clear the results area. resultElement.innerHTML = ""; // Execute the request. wRequest.invoke(); } // This function performs a POST Web request. function PostWebRequest() { alert("Performing Post Web request."); // Instantiate a WebRequest. var wRequest = new Sys.Net.WebRequest(); // Set the request URL. wRequest.set_url("postTarget.aspx"); alert("Target Url: postTarget.aspx"); // Set the request verb. wRequest.set_httpVerb("POST"); // Set the request handler. wRequest.add_completed(OnWebRequestCompleted); // Set the body for he POST. var requestBody = "Message=Hello! Do you hear me?"; wRequest.set_body(requestBody); wRequest.get_headers()["Content-Length"] = requestBody.length; // Clear the results area. resultElement.innerHTML = ""; // Execute the request. wRequest.invoke(); } // This callback function processes the // request return values. It is called asynchronously // by the current executor. function OnWebRequestCompleted(executor, eventArgs) { if(executor.get_responseAvailable()) { // Clear the previous results. resultElement.innerHTML = ""; // Display Web request status. resultElement.innerHTML += "Status: [" + executor.get_statusCode() + " " + executor.get_statusText() + "]" + "<br/>"; // Display Web request headers. resultElement.innerHTML += "Headers: "; resultElement.innerHTML += executor.getAllResponseHeaders() + "<br/>"; // Display Web request body. resultElement.innerHTML += "Body:"; if(document.all) resultElement.innerText += executor.get_responseData(); else resultElement.textContent += executor.get_responseData(); } } if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


这篇关于ASP.Net:发送一个Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆