In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "how to use the ASP.NET AJAX framework for AJAX development", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use the ASP.NET AJAX framework for AJAX development" this article.
First, we can create a WebService service:
[WebService (Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] / / to allow this Web service to be invoked from a script using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WebService1: System.Web.Services.WebService {[WebMethod] public int Add (int a, int b) {return a + b;}
This code is a normal WebService code, except for the fact that a ScriptService decorating feature has been added to the class definition.
Next, we also need to generate a client-side proxy script for it with ScriptManager in an ASPX page:
Note: the setting of InlineScript= "true" is not necessary, just to let us see what code ScriptManager generates.
As you can see from the screenshot, in addition to introducing two necessary AJAX client class libraries, proxy scripts are generated for WebService1 on the client side.
With this code in place, we can invoke the server with the following JavaScript code:
Function Call_Add () {WebService1.Add (1Jing 2, ShowResult);} function ShowResult (result) {document.getElementById ("output"). Value = result;}
The previous example is too simple. Let's take another example with complex parameters. Let's start with the server and define a parameter type:
Public class Customer {public string Name {get; set;} public int Age {get; set;} public string Address {get; set;} public string Tel {get; set;} public string Email {get; set;}}
The code for WebSerice:
[WebMethod] public string AddCustomer (Customer customer) {if (customer = = null) return "customer is null."; / / simply returns a XML string. / / tell the client what kind of data the server has received. Return XmlHelper.XmlSerialize (customer, Encoding.UTF8);}
Still borrowing the previous ScriptManager settings, take a look at the calling code for JavaScript:
Function Call_AddCustomer () {var customer = {Name: document.getElementById ("txtName"). Value, Age: document.getElementById ("txtAge"). Value, Address: document.getElementById ("txtAddress"). Value, Tel: document.getElementById ("txtTel"). Value, Email: document.getElementById ("txtEmail"). Value}; WebService1.AddCustomer (customer, ShowResult);}
Basically, it is similar to the coding method on the server side, first creating a customer object, and then passing it to the calling method.
Before that era (2006), the original AJAX implementation was very complex, and this approach made the client-side code style look very similar to the server-side, which was really a great design idea. However, various technologies have been improving, and now, in 2013, when we look back on this method, we will find that there are indeed some imperfections in it, so that few people use this method now, and this technology has been eliminated!
In fact, we can think from another perspective: if this method is really excellent, it can not be eliminated, it is precisely because there is a better way, it will be eliminated fate.
The improvement direction of new technology
The kind of AJAX method described above can make the client-side calling code basically consistent with the server-side code style, why is the seemingly perfect method eliminated?
Let me analyze the shortcomings of this development approach:
1. The front-end code is not independent enough, and you have to add a reference to the page before you can call the server, which is actually a kind of strong coupling.
two。 There are better front-end frameworks that can easily get less code for calling parameters.
If you continue to read this article, you will find that the new methods I will introduce later are working towards solving these defects, which also point out the direction of improvement of the new technology.
Because the front end needs to generate the proxy script in advance when calling the server, this design will hinder the encapsulation of the front end code. You can imagine that if the client needs a function to get current user information, and this function must be implemented by the server, we can only expect the server to generate a proxy class for the client to invoke this function. But this feature is so useful that it needs to be used in many places. Do you want to extract it into a common file?
Unfortunately: even if you extract this call code into a public public.js file, each page cannot call the get current user Information function after referencing public.js, because the proxy script does not necessarily exist and the code in public.js does not work yet. What shall I do?
A: for each page that references public.js, add ScriptManager to reference that service.
The more common the functionality, the more repetitive you will find this kind of reference code.
Simply put, this approach couples WebService, aspx pages, and js code together.
Because of the coupling, the more you use it, the more troublesome you find it.
Although this development method of generating proxy scripts can make the front-end code consistent with the back-end code, however, the front-end and back-end are not the same development language after all, and they should pay attention to different directions. Especially when a better front-end framework appears, this back-end arranged front-end approach not only couples the back-end with the front-end, but also limits the development of the front-end technology, which can only be abandoned in the end!
Now remember what kind of code we wrote to submit an Customer message:
Var customer = {Name: document.getElementById ("txtName"). Value, Age: document.getElementById ("txtAge"). Value, Address: document.getElementById ("txtAddress"). Value, Tel: document.getElementById ("txtTel"). Value, Email: document.getElementById ("txtEmail"). Value}
When I introduce the fourth generation of technologies, you will find that they are gone!
The second generation technology: jQuery calls WebService directly
With the popularity of random jQuery front-end class libraries, another new development method is also becoming popular.
HTTP call is originally a very simple and transparent technology, as long as you specify a URL and construct a request body, the front-end proxy script method encapsulates this process, because its encapsulation creates coupling and limits the development of the front-end. The new AJAX technology can only break through this limitation, abandon these proxy scripts and call the back-end code directly.
The following sample code is based on the previous example, except that instead of requiring a proxy class, you are now calling the server directly.
Since the back-end service code has not changed, I will no longer post them, and there is no need to add any references to the page, so let's just look at the front-end code:
$.ajax ({type: "POST", url: "/ WebService1.asmx/Add", contentType: "application/json", data: "{a: 1, b: 2}", dataType:'json', success:function (result) {$("# output") .val (result.d);}})
This code can also call the server's Add method.
Because the server uses the JSON data format, you need to specify more request headers on the client, which used to be done by proxy scripts. Although there is a little more code now, the coupling is gone, making it easier to extract some common code.
In fact, if you keep calling WebService in this way, jQuery provides the ability to set default parameters, which we can use to reduce the amount of code.
Let's take a look at the front-end calling code for the previous complex parameter type:
Var customer = {Name: $("# txtName") .val (), Age: $("# txtAge") .val (), Address: $("# txtAddress") .val (), Tel: $("# txtTel") .val (), Email: $("# txtEmail") .val ()}; var jsonStirng = $.tojson ({customer: customer}) $.ajax ({type: "POST", url: "/ WebService1.asmx/AddCustomer", contentType: "application/json", data: jsonStirng, dataType:'json', success:function (result) {$("# output") .val (result.d);}})
The main code is the same, focusing on getting the call parameters, but converting to JSON format.
Once again, instead of focusing on specifying a lot of jQuery parameters, they can be solved by setting default values.
The reason why I don't want them to disappear now is that there is a better way to keep them.
Note: this method can be used not only to call WebService, but also to call WCF (basicHttpBinding). After all, they all use the HTTP protocol. However, WCF still has a lot of annoying configurations to set up, but this is not a problem with jQuery, it is a flaw in the server-side framework.
Third-generation technology: simpler data formats
We saw earlier that we can use jQuery to call WebService, but the conversion process of JSON feels a bit redundant, and the browser submission does not have this conversion step. Sometimes I'm disgusted to see some guys stitching JSON strings in JavaScript, so this time the sample code doesn't discredit that method. I used a JSON plug-in.
The third generation technology perfectly solves the problem that input and output must use JSON, and solves the limitation of POST.
As a result of this change in the data format, so the server has also changed, the new framework to solve these problems, such as: ASP.NET MVC framework, MyMVC framework support this way of development.
Let's take a look at the current server code:
[Action] public int Add (int a, int b) {return a + b;} [Action] public string AddCustomer (Customer customer) {/ / simply returns a XML string. / / tell the client what kind of data the server has received. Return XmlHelper.XmlSerialize (customer, Encoding.UTF8);}
Note: this AJAX technology does not have any coupling with the client, as long as you know a URL can be called. Let's take a look at the client code:
$.ajax ({type: "POST", url: "/ AjaxDemo/Add.cspx", data: {a: 1, b: 2}, success:function (result) {$("# output") .val (result);}}) / / second call var customer = {Name: $("# txtName") .val (), Age: $("# txtAge") .val (), Address: $("# txtAddress") .val (), Tel: $("# txtTel") .val (), Email: $("# txtEmail") .val ()} $.ajax ({type: "POST", url: "/ AjaxDemo/AddCustomer.cspx", data: customer, success:function (result) {$("# output") .val (result);}})
Note: type: "POST" is not required, you can also change them to GET submission.
If you use Fiddler to view the content of the request at this time, you will find that the requested data is in the key=value&key=vlaue format, consistent with the browser. Since there are no restrictions on the JSON data format, the parameter items are now simple.
Now look at the above code, where is the main amount of code?
Are you getting the call parameters?
Keep reading this article, and I'm going to make it disappear.
The fourth generation technology: submit the form directly
Let's take a look at the form used in the example:
New customer information
Name: Age: Address: Tel: Email:
There are three ways to submit this form, so let's take a look at a simpler way to submit:
$(function () {/ / only need the following call to change the form to asynchronous submission! $("# form1") .ajaxForm ({success:function (result) {$("# output") .val (result);});})
In order to demonstrate this method more clearly, I even posted the script tag.
If you have used jQuery, you should be able to find that the real code is only the call to ajaxForm.
Description: ajaxForm is a function provided by the jQuery.form plug-in.
The code on the server side continues to use the code in the previous example, so it is not posted.
Comparing the previous implementation methods of AJAX, which one do you say is the simplest?
Are you interested in the fourth generation AJAX technology?
I have also designed examples for it in three different scenarios to make you feel its power and simplicity. Please read on.
Submission of multiple submit buttons (implemented in jQuery.form)
You think the previous example is too simple, don't you?
Some people may say that if there are multiple submit buttons, this method is not appropriate, I want to respond to each button and assign them a different URL!
Is that true? Take a look at the following example.
The relevant front-end code is as follows:
Input:
Output:
$(function () {$("# form1") .ajaxForm (function (result) {$("# output") .val (result);})
Server code:
Public class AjaxTestAutoAction {[Action] public string Base64 (string input) {return Convert.ToBase64String (Encoding.Default.GetBytes (input));} [Action] public string Md5 (string input) {byte [] bb = Encoding.Default.GetBytes (input); byte [] md5 = (new MD5CryptoServiceProvider ()) .ComputeHash (bb); return BitConverter.ToString (md5) .replace ("-", string.Empty) } [Action] public string Sha1 (string input) {byte [] bb = Encoding.Default.GetBytes (input); byte [] sha1 = (new SHA1CryptoServiceProvider ()) .ComputeHash (bb); return BitConverter.ToString (sha1) .replace ("-", string.Empty);}}
The code is still clear:
1. The server defines three methods that correspond to three submit buttons.
two。 The front end still calls only one ajaxForm to solve all the problems.
This method is implemented by front-end jQuery, jQuery.form and server-side MyMVC framework. Imagine how much code is needed to use the other three methods.
Submission of batch input controls (implemented with jQuery.form)
Let's show another real-world example, the submission of the batch input interface.
The page form code is as follows:
JavaScript Code:
$(function () {$("# form1") .ajaxForm ({success:function (result) {$("# output") .val (result);});})
The server code is as follows:
There is so much code in this example, I don't want to talk about it, and you can figure out how much code you need to use other methods!
Submit complex forms (implemented in jQuery.form)
The previous examples are all direct submission of the form, there is no process of validating the form, and they are all based on Textbox controls, and let's take a complex form example.
The page form code is as follows:
JavaScript Code:
$(function () {$("# form1"). AjaxForm ({beforeSubmit: ValidateForm, success:function (result) {$("# output") .val (result);}); function ValidateForm (formData, jqForm, options) {if (jqForm.context.ProductName.value.length = = 0) {alert ("Product name cannot be empty.") ; $(jqForm.context.ProductName) .focus (); return false;} return true;}})
Server code:
[Action] public string AddProduct (Product product) {/ / simply returns a XML string. / / tell the client what kind of data the server has received. Return XmlHelper.XmlSerialize (product, Encoding.UTF8);} these are all the contents of the article "how to use the ASP.NET AJAX Framework for AJAX Development". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.