How to call the C # method in front-end Javascript (1) Simple implementation (with source code)

Source: Internet
Author: User

I believe many of my friends have come up with this idea when they are new to WebForm programming. Why cannot I directly call the method in the. aspx. cs file in Javascript ON THE. aspx page? The content introduced in this article is somewhat related to this issue, but it does not really solve the problem of directly calling the C # method in Javascript, it is just a little simpler to implement the interaction between the front-end and the back-end through other methods. The content of this article is a little bit of my accumulated experience in the actual development process, we may wish to discuss something wrong or something better.
I don't need to introduce Ajax too much. I believe you may know more about it. When some static (or pseudo-static) pages require dynamic updates, ajax is used a lot, and there are many ways to process Ajax requests. Some friends directly create a new one. aspx page, and then in. aspx. response. write, some friends prefer to use. some friends prefer IHttpHandler. IHttpHandler is used in this article.
Generally, the content that requires dynamic output is more or less related to the business logic. In this example, the code is divided into two projects, the Web project is only responsible for data display, and the Biz project is responsible for logical processing. The Demo code is only a simple example. The code in the actual development project may be very different.
Next we will go to the topic to discuss what we want to implement.
On the html page, we can directly access the specified method of a class in the Biz project through the link of the specified rule.
For example, if you request/Ajax/News/GetNewsHits. aspx, you can call the GetNewsHits method in the News class of the Biz project.
Since we all know that direct calling is impossible, we must have a proxy to help us complete the intermediate process.

First, create an Ajax folder under the root directory of the Web project and add a web. config file. The Code is as follows:
View Code
<? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<AppSettings/>
<ConnectionStrings/>
<System. web>
<HttpHandlers>
<Add path = "*. aspx" validate = "false" type = "Biz. Factory" verb = "*"/>
</HttpHandlers>
</System. web>
<System. webServer>
<Handlers>
<Add name = "AjaxRequestFactory" path = "*. aspx" type = "Biz. Factory" verb = "*"/>
</Handlers>
</System. webServer>
</Configuration>

This Code indicates that all aspx file requests in the Ajax folder are handed over to the "Biz. Factory" class for processing.
 
Then we add the class "Factory" in the Biz project, that is, our proxy class, which is responsible for transferring requests to the specified method and implementing the IHttpHandler interface. The Code is as follows:
View Code
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Web;

Namespace Biz {
Public class Factory: IHttpHandler {
Public bool IsReusable {
Get {
Return true;
}
}

Public void ProcessRequest (HttpContext context ){
Execute (context );
}

Void Execute (HttpContext context ){
// Obtain the class for processing the request through reflection based on the request Url
String url = context. Request. Url. AbsolutePath;
String [] array = url. Split (new char [] {'/'}, StringSplitOptions. RemoveEmptyEntries );
String typename = "Biz ";
For (int x = 1; x <array. Length-1; x ++ ){
Typename + = "." + array [x];
}
Type type = this. GetType (). Assembly. GetType (typename, false, true );
If (type! = Null ){
// Obtain the non-parameter constructor of the class
Var constructor = type. GetConstructor (new Type [0]);
// Call the constructor to obtain an instance of the class
Var obj = constructor. Invoke (null );
// Query the Request Method
Var method = type. GetMethod (System. IO. Path. GetFileNameWithoutExtension (url ));
If (method! = Null ){
// Execute the method and output the response result
Context. Response. Write (method. Invoke (obj, null ));
}
}
}
}
}

 
Of course, we also need a class News called for Demonstration:
View Code
1 using System;
2 using System. Collections. Generic;
3 using System. Linq;
4 using System. Text;
5
6 namespace Biz {
7 public class News {
8 static int _ value;
9 public int GetNewsHits (){
10 return ++ _ value;
11}
12}
13}

 
Finally, return to the web project and create an html file. The code is very simple. ajax will not repeat the code and directly use the relevant methods in jquery:
View Code
<! 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>
<Script language = "javascript" type = "text/javascript" src = "Scripts/jquery-1.4.1.min.js"> </script>
<Script language = "javascript" type = "text/javascript">
$ (Function (){
// Bind button click event
$ ("Input: button"). click (function (){
$. Post ("/Ajax/News/GetNewsHits. aspx", null, function (txt ){
$ ("Div"). text (txt );
}, "Text ");
});
});
</Script>
</Head>
<Body>
<Div style = "font-size: 24px; font-weight: bold; width: 100px; line-height: 35px; text-align: center;"> 0 </div>
<Input type = "button" value = "retrieve clicks"/>
</Body>
</Html>

 
After all the code is ready, there are actually few lines of code. Classes and methods in the Biz project can be added at will, just change the call link.
Download Sample Code: Click to download
Http://www.bkjia.com/uploadfile/2012/0308/20120308082911918.zip
 
Sample Code Description:
1. You need to run the project to see the demo effect.
2. Each time you click the button, the server will accumulate 1 and return.
3. You can also add another method to the Biz. News class for testing. Of course, the GetNewsHits in the call link must be changed to your corresponding method name.
4. You can also add a new class to the Biz project to test the function. The condition is that the new class must have no parameter constructor.
 
To be continued...
 

 

From Wolf Robot

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.