简体   繁体   English

自定义Javascript Ajax for ASP.NET

[英]Custom Javascript Ajax for ASP.NET

I've written some basic Javascript functions and would like to learn how to enable asynchronous postbacks within a C# 4.0/ASP.net project using this JS code. 我已经编写了一些基本的Javascript函数,并想学习如何使用这个JS代码在C#4.0 / ASP.net项目中启用异步回发。

For example, I have a script that increments a number when clicked. 例如,我有一个脚本,单击时会增加一个数字。 When clicked again, the number is decremented. 再次单击时,数字会递减。 I basically load the number from a database, then hide one <span> and show another with the corresponding decremented number on click. 我基本上从数据库加载数字,然后隐藏一个<span>并在点击时显示另一个带有相应的递减数字。 This is not complicated javascript; 这不是复杂的javascript; its a simple example. 这是一个简单的例子。 Now when I click the button I want to send this increment/decrement call back to the server to update the database's number. 现在,当我单击按钮时,我想将此递增/递减调用发送回服务器以更新数据库的编号。

I realize that I can accomplish something akin to this example using the AJAX Control Toolkit's toggle button. 我意识到我可以使用AJAX Control Toolkit的切换按钮完成类似于此示例的操作。 I, however, want to know how to use my OWN javascript to create AJAX functionality. 但是,我想知道如何使用我的OWN javascript来创建AJAX功能。

How do I accomplish this using C# and my custom Javascript code? 如何使用C#和我的自定义Javascript代码完成此操作?

I'm not opposed to using the ASP.net AJAX library, I just don't want to use a ready built control. 我并不反对使用ASP.net AJAX库,我只是不想使用现成的控件。 I want to learn the process of creating my own AJAX functionality. 我想学习创建自己的AJAX功能的过程。 I would presume that I will have to use an asp:UpdatePanel , but I don't know how to call C# functions from the client side. 我认为我将不得不使用asp:UpdatePanel ,但我不知道如何从客户端调用C#函数。

My javascript is not jQuery, in fact I want nothing to do with jQuery until I learn more about javascript and this process. 我的javascript不是jQuery,事实上我想要与jQuery无关,直到我了解更多关于javascript和这个过程。

Simple with no UpdatePanel: 没有UpdatePanel的简单:

First, add a Generic Handler to your project (.ashx). 首先,为项目添加一个通用处理程序(.ashx)。 This will act as our Http endpoint. 这将充当我们的Http端点。 Our javascript will call it. 我们的javascript会调用它。 We could (and probably should), use a web service endpoint but that requires processing the response and complicates the example. 我们可以(也可能应该)使用Web服务端点,但这需要处理响应并使示例复杂化。 A handler returns plain text. 处理程序返回纯文本。

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler
{
    // We'll use a static var as our "database".
    // Feel free to add real database calls to the increment
    // and decrement actions below.
    static int TheNumber = 0;

    public void ProcessRequest(HttpContext context)
    {       
        string action = context.Request.QueryString["action"];
        if (!string.IsNullOrEmpty(action))
        {
            if (action == "increment")
                TheNumber++;   //database update and fetch goes here
            else if (action == "decrement")
                TheNumber--;   //database update and fetch goes here           
        }
        context.Response.ContentType = "text/plain";
        context.Response.Write(TheNumber);
    }

    public bool IsReusable { get { return false; } }
}

Next, create your web page and add the async javascript. 接下来,创建您的网页并添加异步javascript。

<%@ Page Language="C#"%>
<html>
<head runat="server">    
    <script type="text/javascript">
    // An XMLHttpRequest object is required to make HTTP requests.
    // Try a couple instantiation strategies to handle different
    // browser implementations.
    function createXMLHttpRequest() {
        try { return new XMLHttpRequest(); } catch (e) { }
        try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
        try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
        alert("XMLHttpRequest not supported");
        return null;
    }

    function callHandler(action) {
        var xmlHttpReq = createXMLHttpRequest();
        // We're interested in an asychronous request so we define a 
        // callback function to be called when the request is complete.
        xmlHttpReq.onreadystatechange = function () {
            if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
                document.getElementById("<%= lbl.ClientID%>").innerHTML 
                    = xmlHttpReq.responseText;
        }
        xmlHttpReq.open("GET", "Handler.ashx?action=" + action, true);
        xmlHttpReq.send(null);
    }  
    </script>
</head>
<body>
    <form id="Form1" runat="server">
    <div>
    The Number:&nbsp;<Label runat="server" id="lbl">0</Label>
    </div>
    <div>
        <asp:Button ID="Button1" runat="server" Text="Increment" 
            OnClientClick="callHandler('increment');return false;" />
        &nbsp;
        <asp:Button ID="Button2" runat="server" Text="Decrement" 
            OnClientClick="callHandler('decrement');return false;" />
    </div>
    </form>
</body>
</html>

The final flow is: 最后的流程是:

  • A web page user clicks the Increment or Decrement button which calls our javascript 网页用户单击调整我们的javascript的递增或递减按钮
  • Our javascript sends a request with the desired action in the querystring to Handler.ashx 我们的javascript在查询字符串中向Handler.ashx发送带有所需操作的请求
  • Handler.ashx reads the querystring, increments or decrements its static variable, and returns the value Handler.ashx读取查询字符串,递增或递减其静态变量,并返回该值
  • Our callback receives the value and updates our UI. 我们的回调接收值并更新我们的UI。

if your using an UpdatePanel it's very simple with a JavaScript call to __doPostBack . 如果您使用UpdatePanel则通过对__doPostBack的JavaScript调用非常简单。 See here for example . 例如,这里

Have a look at this tutorial around AJAX http://www.w3schools.com/Ajax/Default.Asp 看看有关AJAX的本教程http://www.w3schools.com/Ajax/Default.Asp

It will give you an overview of using Javascript to GET and POST data using AJAX. 它将概述使用JAX使用AJAX获取GET和POST数据。

Hope this helps. 希望这可以帮助。

Here's a link on how you can incorporate ASP.NET C# with your custom Javascript code. 以下是有关如何将ASP.NET C#与自定义Javascript代码合并的链接。

http://msdn.microsoft.com/en-us/library/bb386450.aspx http://msdn.microsoft.com/en-us/library/bb386450.aspx

It also contains a sample VS 2010 project here: http://go.microsoft.com/fwlink/?LinkId=185646 它还包含一个示例VS 2010项目: http//go.microsoft.com/fwlink/?LinkId = 185646

Here's generally what's going on here: 这里通常是这里发生的事情:

In the AjaxIScriptControl solution: AjaxIScriptControl解决方案中:

SampleTextBox.cs - takes care of rendering the script control on the page; SampleTextBox.cs - 负责在页面上呈现脚本控件; and attachment to client javascript code (the js file) 和客户端javascript代码(js文件)的附件

SampleTextBox.js - takes care of client side functionality and generates Javascript object of control via prototype SampleTextBox.js - 负责客户端功能并通过原型生成Javascript控制对象

Notes: 笔记:

  • This example leverages existing ASP.NET's built-in control (you notice SampleTextBox inherits Textbox and IScriptControl) but you can render any type of HTML control if you inherit ScriptControl class instead. 此示例利用现有ASP.NET的内置控件(您注意到SampleTextBox继承了Textbox和IScriptControl),但如果您继承ScriptControl类,则可以呈现任何类型的HTML控件。

  • This solution also chose to separated the Script control code and website code in two projects but you can easily make it into one. 此解决方案还选择在两个项目中分离脚本控制代码和网站代码,但您可以轻松地将其合并为一个。

  • You can easily leverage another Javascript library in your JS file 您可以轻松利用JS文件中的另一个Javascript库

In my experience so far, this is the one of the more elegant way to incorporate server side code with client side if you are to create re-useable controls for your website. 根据我的经验,如果要为您的网站创建可重复使用的控件,这是将服务器端代码与客户端相结合的更优雅方式之一。 You leverage server side power to do the initial rendering while provide client side capabilities through Javascript. 您利用服务器端功能进行初始渲染,同时通过Javascript提供客户端功能。

If you create your C# functions as WCF REST Services or older-style Script Services , then you can easily call your service methods from your JavaScript using a basic XmlHttpRequest (no jQuery or UpdatePanels needed). 如果您将C#函数创建为WCF REST服务或旧式脚本服务 ,则可以使用基本的XmlHttpRequest(无需jQuery或UpdatePanels)轻松地从JavaScript调用服务方法。

Here's a quick jsFiddle I put together: http://jsfiddle.net/ndVeS/ 这是我放在一起的快速jsFiddle: http//jsfiddle.net/ndVeS/

This sample has two text boxes; 此示例有两个文本框; you enter a value in the first one, click the button, and then that value is passed to a service (an echo service) and returned in the callback. 在第一个中输入一个值,单击该按钮,然后将该值传递给服务(回显服务)并在回调中返回。 The JavaScript code takes that value and populates the second textbox with it. JavaScript代码获取该值并使用它填充第二个文本框。

You could define a C# WCF RESTful service like this: 您可以像这样定义C#WCF RESTful服务:

[ServiceContract]
public class EchoService : IEchoService {
  [WebGet(UriTemplate="EchoMe?val={theValue}, ResponseFormat=WebMessageFormat.Json)]
  public string EchoMe(string theValue) {
    return theValue;
  }
}

If you handle your calls this way, you can separate out your service logic from your presentation (ASPX files), and this allows for easier testing and you can also separate responsibilities from those who build the UI from those that build the business functionality. 如果以这种方式处理您的调用,您可以将您的服务逻辑与您的演示文稿(ASPX文件)分开,这样可以更轻松地进行测试,您还可以将构建UI的人员与构建业务功能的人员分开。

I have to admit I'm more of a jQuery person when it comes to this, but I thought it's a great exercise to figure out how the XmlHttpRequest works under the hood. 我不得不承认,在谈到这一点时,我更像是一个jQuery人,但我认为这是一个很好的练习,可以弄清楚XmlHttpRequest是如何工作的。 It makes you appreciate what jQuery (or similar framework) provides. 它让你欣赏jQuery(或类似的框架)提供的东西。

Here's a nice overview of the XmlHttpRequest object and how to use it: http://www.jibbering.com/2002/4/httprequest.html 这里是XmlHttpRequest对象的一个​​很好的概述以及如何使用它: http//www.jibbering.com/2002/4/httprequest.html

I hope this helps. 我希望这有帮助。

function GetXmlHttpObject(handler) {
var objXMLHttp = null
if (window.XMLHttpRequest) {
    objXMLHttp = new XMLHttpRequest()
}
else if (window.ActiveXObject) {
    objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp;

} }

function GetDropDown() { function GetDropDown(){

function stateChanged(StatesUpdated) {


    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
        document.getElementById('updateplace').innerHTML = xmlHttp.responseText;
        //"updateplace" is you div id which will hold the new data or new page
        if (navigator.appName != "Microsoft Internet Explorer") {

        }
    }
    else {
        //alert(xmlHttp.status);
    }
}





xmlHttp = GetXmlHttpObject()
if (xmlHttp == null) {
    alert("Browser does not support HTTP Request");
    return;
}



    url = "xyz.aspx" //this might be sent to any post data
    url = url + "&sid=" + Math.random();


    xmlHttp.onreadystatechange = stateChanged;

    xmlHttp.open("GET", url, true);

    xmlHttp.send(null);

} }

with the above code you can send data to any .cs file also where you can change the data and load it in a new page which will load in the update div and the method should redirect to the new aspx file. 使用上面的代码,您可以将数据发送到任何.cs文件,您也可以在其中更改数据并将其加载到将加载到更新div中的新页面中,并且该方法应重定向到新的aspx文件。

I hope you got the logic :) 我希望你有逻辑:)

if you have any doubts reach me @ sankalpa.sam@gmail.com 如果您有任何疑问,请联系我@ sankalpa.sam@gmail.com

I know it's not MVC that you're doing, but have a look at the MVC section of the ASP.NET site and you will find a lot of examples of AJAX calls there - MVC doesn't use those dreadful script-soup creating .NET objects. 我知道你正在做的不是MVC,但是看一下ASP.NET网站的MVC部分,你会发现很多AJAX调用的例子--MVC不会使用那些可怕的脚本创建。 NET对象。 Most will probably be using jQuery - this is an open-source javascript library that can plug into any web app and provides some really nice functionality. 大多数人可能会使用jQuery - 这是一个开源的JavaScript库,可以插入任何Web应用程序并提供一些非常好的功能。

Maybe ur looking for this: 也许你在寻找这个:

function ajaxscript(){ $.ajax({ type: "POST", url: |url/methodName|, data: |variable_name|, contentType: "application/json; charset=utf-8", dataType: "json", success: |some javascript here|, error: |some javascript here| }); function ajaxscript(){$ .ajax({type:“POST”,url:| url / methodName |,data:| variable_name |,contentType:“application / json; charset = utf-8”,dataType:“json”,成功:|一些javascript在这里|,错误:|一些javascript在这里|});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM