GET and POST Calls to Controller's Method in MVC

In this article I am going to cover some really interesting material that is very useful today in web application developments. You will learn how to make jQuery Ajax GET and POST calls to controller methods.

When we use jQuery Ajax to access a server (controller's method) without reloading the web page we have two choices for how to pass the information for the request to the server (controller's method). These two options are to use either GET or POST.

Note: Before beginning with the code, ensure you are using the jQuery library before the GET or POST script.

GET

GET is used to request data from a specified resource. With all the GET request we pass the URL which is compulsory, however it can take the following overloads.

  1. .get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ).done/.fail  
Now, let's try to use GET in MVC application.

GET call to Controller's Method that will return string data

Let's imagine we have the following method in the controller:
  1. public string TellMeDate()  
  2. {  
  3.     return DateTime.Today.ToString();  
  4. }  
This method will return string data (date-time) when we call it, let's make an async call using jQuery Ajax.
  1. <p id="rData">  
  2. </p>   
  3. <script type="text/jscript">  
  4.     var url = "/Home/TellMeDate";  
  5.     $.get(url, nullfunction (data) {  
  6.         $("#rData").html(data);  
  7.     });  
  8. </script>  
When the page gets loaded, jQuery Ajax will generate an Ajax GET request/call. The first parameter is the URL and the second is data (this is an optional, even we can avoid typing "null") and the third is the success function when the response is received. The success function takes one parameter "data" that holds the string content and we attached this content to a DOM element.

If you want to generate an Ajax GET request when the user clicks a button then can use the following instead:
  1. <script type="text/jscript">  
  2.     $('#ButtonID').click(function () {  
  3.         var url = "/Home/TellMeDate";  
  4.         $.get(url, nullfunction (data) {  
  5.             $("#rData").html(data);  
  6.         });  
  7.     })  
  8. </script>  
If you run the application, you will see the following output:

1.png

GET call with parameter to Controller's Method that will return string data
 
Let's imagine we have the following method in the controller: 
  1. public string WelcomeMsg(string input)  
  2. {  
  3.     if (!String.IsNullOrEmpty(input))  
  4.         return "Please welcome " + input + ".";  
  5.     else  
  6.         return "Please enter your name.";  
  7. }   
This method will accept a parameter and will return string data (a welcome message or instruction message) when we call it. Now, let's make an async call to this method using jQuery Ajax. 
  1. <p>  
  2.     Enter you name @Html.TextBox("Name")  
  3.     <input type="submit" id="SubmitName" value="Submit"/>  
  4. </p>   
  5. <script type="text/jscript">  
  6.     $('#SubmitName').click(function () {  
  7.         var url = "/Home/WelcomeMsg";  
  8.         var name = $('#Name').val();  
  9.         $.get(url, { input: name }, function (data) {  
  10.             $("#rData").html(data);  
  11.         });  
  12.     })  
  13. </script>   
As you can see, when we click the button after typing a name in the TextBox, jQuery Ajax will generate an Ajax GET request/call. Notice that the second parameter to the "get" function now contains a key { input: name } (parameter). This example supplies one parameter, but can be extended to provide multiple parameters. The result of the preceding looks like the following: 


GET call with parameter to Controller's Method that will return JSON data
 
The Controller's method we used above returns simple strings. Now, to deal with complex data we need JSON. The following method will return a JsonResult having the customer's ContactName and Address from NorthwindEntities. I am using the Northwind database and EF Database First approach in this sample. 

  1. public JsonResult CustomerList(string Id)  
  2. {  
  3.     NorthwindEntities db = new NorthwindEntities();  
  4.     var result = from r in db.Customers  
  5.                     where r.Country == Id  
  6.                     select new { r.ContactName, r.Address };  
  7.     return Json(result, JsonRequestBehavior.AllowGet);  
  8. }   
The above method will accept Id as a parameter and return a "JsonResult". This action method can be called using the following jQuery Ajax GET call: 
  1. <p id="rData">  
  2. </p>   
  3. <p>  
  4.     Enter country name @Html.TextBox("Country")  
  5.     <input type="submit" id="GetCustomers" value="Submit"/>  
  6. </p>   
  7. <script type="text/jscript">  
  8.     $('#GetCustomers').click(function () {  
  9.         $.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {   
  10.             var items = '<table><tr><th>Name</th><th>Address</th></tr>';  
  11.             $.each(data, function (i, country) {  
  12.                 items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";  
  13.             });  
  14.             items += "</table>";   
  15.             $('#rData').html(items);  
  16.         });  
  17.     })  
  18. </script>   
As you can see, when we click the button after typing a country name in the TextBox, jQuery Ajax will generate an Ajax GET request/call. Notice that the "getJSON" function now contains an URL in the format "/Controller/ActionMethod/Key", here the key (parameter) is the supplied country name. The result of the preceding looks like the following:



Using Firebug we can sniff the response. A screen shot is shown below: 



In the above example we have used a TextBox where we typed the country name and clicked on a button to get the list of customers.
 
Alternatively, we can populate the list of countries in the dropdownlist box and then when the user selects the country name from the dropdownlist, we can display the list of customers.   


Here is the controller that will populate the country list in the dropdownlist box: 

  1. public ActionResult About()  
  2. {  
  3.     var result = from r in db.Customers  
  4.                     select r.Country;  
  5.     ViewBag.Country = result;   
  6.     return View();  
  7. }   
 Now, once we have a list of countries in the dropdownlist box, we can implement an Ajax GET request/call. Here it is with a complete view page. 
  1. @Html.DropDownListFor(model => model.Country, new SelectList(ViewBag.Country), "Select Country")   
  2. <p id="rData">  
  3. </p>   
  4. @section Scripts {  
  5.     <script type="text/jscript">  
  6.         $('#Country').click(function () {  
  7.             $.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {   
  8.                 var items = '<table><tr><th>Name</th><th>Address</th></tr>';  
  9.                 $.each(data, function (i, country) {  
  10.                     items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";  
  11.                 });  
  12.                 items += "</table>";   
  13.                 $('#rData').html(items);  
  14.             });  
  15.         })  
  16.     </script>  
  17. }   
Everything remains the same as in the TextBox version above.
 
POST
 
POST is used to submit data to be processed to a specified resource. With all the POST requests we pass the URL which is compulsory and the data, however it can take the following overloads.  
  1. .post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )   
Now, let's try to use POST in a MVC application.
 
POST call to Controller's Method to save TextBox data (not form)
 
There are various ways to POST form data to a method but in the example given below I'm not going to use any form. I will just use two textboxes and a submit button, when the user clicks the button I want to save the data using a jQuery Ajax POST call. So, here is the method accepting the two parameters for name and address: 
  1. [HttpPost]  
  2. public string SubmitSubscription(string Name, string Address)  
  3. {  
  4.     if (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Address))  
  5.         //TODO: Save the data in database  
  6.         return "Thank you " + Name + ". Record Saved.";  
  7.     else  
  8.         return "Please complete the form.";             
  9. }   
 We can implement method above to save the data in the database, it will also return the response back to the client. Here is the jQuery Ajax POST function: 
  1. <h2>Subscription</h2>   
  2. <p>  
  3.     Enter your name  
  4.     <br />  
  5.     @Html.TextBox("Name")  
  6. </p>  
  7. <p>  
  8.     Enter your address  
  9.     <br />  
  10.     @Html.TextBox("Address")  
  11. </p>   
  12. <input type="button" value="Save" id="Save" />  
  13. <span id="msg" style="color:red;"/>   
  14. <script type="text/javascript">  
  15.     $('#Save').click(function () {  
  16.         var url = "/Home/SubmitSubscription";  
  17.         var name = $("#Name").val();  
  18.         var address = $("#Address").val();  
  19.         $.post(url, { Name: name, Address: address }, function (data) {  
  20.             $("#msg").html(data);  
  21.         });  
  22.     })  
  23. </script>   
 When you run the application above it will look like the following:

 



POST call to Controller's Method to save form data

In case above we don't have a form, so I have used two individual properties/parameters (name and address) with a jQuery Ajax POST call and also on the method side, but this approach will be painful since the number of properties increase. In this case we can use the model approach that will allow us to work with intelisense. So, let's go and create the "Subscription" model class with two properties.

  1. public class Subscription  
  2. {  
  3.     public string Name { get; set; }  
  4.     public string Address { get; set; }  
  5. }  
Now that we have the model we can create our controller method:
  1. [HttpPost]  
  2. public string SubmitSubscription(Subscription subs)  
  3. {  
  4.     if (!String.IsNullOrEmpty(subs.Name) && !String.IsNullOrEmpty(subs.Address))  
  5.         //TODO: Save the data in database  
  6.         return "Thank you " + subs.Name + ". Record Saved.";  
  7.     else  
  8.         return "Please complete the form.";             
  9. }  
Still the same, just using a model instead of individual properties.
  1. <h2>Subscription</h2>   
  2. <form id="subscriptionForm" action="/Home/SubmitSubscription" method="post">  
  3. <p>  
  4.     Enter your name  
  5.     <br />  
  6.     @Html.TextBox("Name")  
  7. </p>  
  8. <p>  
  9.     Enter your address  
  10.     <br />  
  11.     @Html.TextBox("Address")  
  12. </p>   
  13. <input type="button" value="Save" id="Save" />  
  14. <span id="msg" style="color:red;"/>  
  15. </form>   
  16. @section Scripts{  
  17.     <script type="text/javascript">  
  18.         $('#Save').click(function () {   
  19.             var form = $("#subscriptionForm");  
  20.             var url = form.attr("action");  
  21.             var formData = form.serialize();  
  22.             $.post(url, formData, function (data) {  
  23.                 $("#msg").html(data);  
  24.             });  
  25.         })  
  26.     </script>  
  27. }  
Noting new, everything is the same, just a few changes that allow us to work with a form.

Hope this helps.