The principle
In fact, to call a server-side method from Javascript code, there is only one method: you have to launch an HTTP request.
To understand the operation, we must distinguish the two parts of the application:
Part of the application is run on the Web server (C # code),
Part is executed in the browser (Javascript code).
The two parts are separate and can only communicate via HTTP requests (GET, POST or other actions).
To make an action to the server, it is necessary to launch an HTTP request with Javascript. This is greatly simplified with libraries like jQuery for example.
The concrete example
To better understand, I propose a simple example using ASP.NET MVC server side and Javascript with jQuery client side.
Server side:
We develop a controller named “ServiceController”. This contains a “GetStats” method.
With the default routing of ASP.NET MVC, it is possible to call the method directly from the browser. The URL will be of type “/ Service / GetStats”.
It remains to write a piece of code to call this address from Javascript.
Customer side:
To call a server URL from Javascript, you can use the HTTP GET method or the POST method.
POST is generally used when there are many elements to transmit (for example for the submission of a form).
In the example, we will use GET for simplicity.
In Javascript, just write this piece of code to make the call:
1 2 3 4 5 | $ .get ('/ Service/GetStats', function() { // code executed after the server response }); |
You will notice that it is possible to execute Javascript code when receiving the response from the server. Generally, this code allows to update the page in the browser.
Complete project
I have prepared a complete project for you to download so that you can better understand the example.
This project demonstrates how:
- View a page that has an action button
- Add this button in Javascript to intercept the click,
- Launch a request to the server from Javascript,
- Update the web page with the result of the server,
- Write a simple action that returns a string with ASP.NET MVC.