...

Using simple javascript to call server side method in Asp.Net MVC.

Lets see how we can make server side call using pure javacscript. Below is a javascript class to make http GET request using XMLHttpRequest() object. 

var HttpClient = function() {
 this.get = function(url, callback) {
 var httpRequest = new XMLHttpRequest();
 httpRequest.onreadystatechange = function() { 
 if (httpRequest.readyState == 4 && httpRequest.status == 200)
 callback(httpRequest.responseText);
 }

httpRequest.open( "GET", url, true ); 
 httpRequest.send( null );
 }
}

 

Usage: use httpClient object to make get call with the url passing parameter.

var client = new HttpClient();
client.get('/Home/GetItem?id=4', function(response) {
 // do something with response
});

 

Controller method: In MVC controller create ActionResult method with  HttpGet attribute to receive httpGet call with integer parameter id.

[HttpGet]
 public ActionResult GetItem(int id)
 {
 var itemId = id;
 //do some stuff
 return View();
 }

 
Similarly we can add post function to above class, we have to set request header for the Content-type and pass data while making httpPost request.

this.post = function (url, callback, data) {
 var httpRequest = new XMLHttpRequest();
 httpRequest.onreadystatechange = function () {
 if (httpRequest.readyState == 4 && httpRequest.status == 200)
 callback(httpRequest.responseText); 
 }

httpRequest.open("POST", url, true);
 httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 httpRequest.send(data);
 }

 

Usage: passing parameter, here we have set Id value 4 to send data with POST request. On sucess show some message.

var data = "Id=" + 4;
client.post('/Home/GetItem', function (response) {
console.log('done successfully.');
}, data);

 

Controller Method: In MVC controller create same Action method above GetItem with HttpPost attribute. To get the data use Request.Form with the parameter name to receive send data. 

[HttpPost]
 public ActionResult GetItem()
 {
 var itemId = Request.Form["Id"];
 //do some stuff
 return View();
 }

We have learn above how to send httpGet and httpPost request using simple javascript. It can be used while loading a widget or container data.

Back to top