Get and Post Method in json Ajax in MVC

Get Method Call

I have to explain in 3 ways:

  1. Simple Return the Message what you type on Textbox using JsonResult. The .cshtml Page Lokks Like:
    1. <script type="text/javascript">  
    2.     $(document).ready(function () {  
    3.      $('#SubmitName').click(function () {  
    4.             var url = "../Home/InputMessage";  
    5.             var name = $('#Name').val();  
    6.             $.get(url, { input: name }, function (data) {  
    7.                 $("#rData").html(data);  
    8.             });  
    9.         })  
    10.     });  
    11. </script>  
    12. <div>  
    13.     <p>  
    14.         Enter you name @Html.TextBox("Name")  
    15.   
    16.         <input type="submit" id="SubmitName" value="Submit"/>  
    17.     </p>  
    18.     <p id="rData"></p>  
    19. </div>  
    Add the Method in Controller that simply return the Message.
    1. public string InputMessage(string input)  
    2. {  
    3.    if (!String.IsNullOrEmpty(input))  
    4.       return "TextBox Value is =====> " + input + ".";  
    5.    else  
    6.       return "Please enter your name.";  
    7. }  
  2. Using Textbox Filter the data.
    1. <h1>Filter Data With Get Metohod using Json Result</h1>  
    2. <p id="rDataT"></p>  
    3. <style>  
    4.     table, th , td {  
    5.         border: 1px solid grey;  
    6.         border-collapse: collapse;  
    7.         padding: 5px;  
    8.     }  
    9.     table tr:nth-child(odd) {  
    10.         background-color: #f1f1f1;  
    11.     }  
    12.     table tr:nth-child(even) {  
    13.         background-color: #ffffff;  
    14.     }  
    15. </style>  
    16. <p>  
    17.     Enter Filter @Html.TextBox("Filter")  
    18.   
    19.     <input type="submit" id="GetCustomers" value="Submit"/>  
    20. </p>  
    21. <script type="text/jscript">  
    22.     $('#GetCustomers').click(function () {  
    23.         $.getJSON('../Home/GetStudentList/' + $('#Filter').val(), function (data) {  
    24.             var items = '  
    25.             <table>  
    26.                 <tr>  
    27.                     <th>Student Name</th>  
    28.                     <th>Student Admission Number</th>  
    29.                 </tr>';  
    30.                 $.each(data, function (i, item) {  
    31.                     items += "  
    32.                     <tr>  
    33.                         <td>" + item.StdName + "</td>  
    34.                         <td>" + item.AdmNo + "</td>  
    35.                     </tr>";  
    36.                 });  
    37.                 items += "  
    38.             </table>";  
    39.             $('#rDataT').html(items);  
    40.         });  
    41.     })  
    42.   
    43. </script>  
    Also call the json result in controller : On the below i have Linq to SQL.
    1. public JsonResult GetStudentList(string id)  
    2. {  
    3.    DataClasses1DataContext db = new DataClasses1DataContext();  
    4.    var result = from r in db.StudentMasters  
    5.    where r.StdName.StartsWith(id)  
    6.    select new { r.StdName, r.AdmNo };  
    7.    return Json(result, JsonRequestBehavior.AllowGet);  
    8. }  
  3. On button Click get the Static Data.
    1. <input id="btnGet" type="button" value="Get Data From List" />  
    2. <div>  
    3.     <div id="ajaxDiv"></div>  
    4. </div>  
    5. <script type="text/javascript">  
    6.     $(document).ready(function () {  
    7.         $('#btnGet').click(function () {  
    8.             $.getJSON("../Home/GetJsonData"null, function (data) {  
    9.                 var div = $('#ajaxDiv');  
    10.                 div.html("  
    11.                 <br/> " + "Fetch from json Static List: " + "  
    12.                 <br/>");  
    13.                 $.each(data, function (i, item) {  
    14.                     printPerson(div, item);  
    15.                 });  
    16.             });  
    17.         });  
    18.     });  
    19.     function printPerson(div, item) {  
    20.         var tbl = "";  
    21.         div.append("  
    22.         <br/>" + "FName: " + item.FirstName + ", LName: " + item.LastName);  
    23.         $.each(item.Addresses, function (i, addr) {  
    24.             printAddress(div, addr);  
    25.         });  
    26.     }  
    27.     function printAddress(div, item) {  
    28.         div.append("  
    29.         <br/>" + " " + "Address: " + item.currentAddress);  
    30.     }  
    31.   
    32. </script>  
    In the controller class looks like:
    1. public JsonResult GetJsonData() {  
    2.     var persons = new List < Person > {  
    3.         new Person {  
    4.             Id = 1, FirstName = "Jayant",  
    5.             LastName = "Tripathy",  
    6.             Addresses = new List < Address > {  
    7.                 new Address {  
    8.                     currentAddress = "xyz"  
    9.                 },  
    10.             }  
    11.         },  
    12.         new Person {  
    13.             Id = 2, FirstName = "Sri",  
    14.             LastName = "Alex",  
    15.             Addresses = new List < Address > {  
    16.                 new Address {  
    17.                     currentAddress = "Delhi"  
    18.                 },  
    19.             }  
    20.         }  
    21.     };  
    22.     return Json(persons, JsonRequestBehavior.AllowGet);  
    23. }  
    Also add the property classes:
    1. public class Person  
    2. {  
    3.    public int Id { getset; }  
    4.    public string FirstName { getset; }  
    5.    public string LastName { getset; }  
    6.    public List<Address> Addresses { getset; }  
    7. }  
    8. public class Address  
    9. {  
    10.    public string currentAddress { getset; }  
    11. }  
    The Final code of GET method .cshtml is:
    1. @{  
    2. ViewBag.Title = "FormGet";  
    3. }  
    4.   
    5. <!DOCTYPE html>  
    6. <html>  
    7.     <head>  
    8.         <meta name="viewport" content="width=device-width" />  
    9.         <title>FormGet</title>  
    10.         <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"  
    11. rel="stylesheet" type="text/css"/>  
    12.         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>  
    13.     </head>  
    14.     <script type="text/javascript">  
    15.         $(document).ready(function () {  
    16.             $('#SubmitName').click(function () {  
    17.                 var url = "../Home/InputMessage";  
    18.                 var name = $('#Name').val();  
    19.                 $.get(url, { input: name }, function (data) {  
    20.                     $("#rData").html(data);  
    21.                 });  
    22.             })  
    23.         });  
    24.     </script>  
    25.     <body>  
    26.         <div>  
    27.             <p>  
    28. Enter you name @Html.TextBox("Name")  
    29.   
    30.                 <input type="submit" id="SubmitName" value="Submit"/>  
    31.             </p>  
    32.             <p id="rData"></p>  
    33.         </div>  
    34. ------------------------------------------------------------------------------------------------------  
    35.   
    36.         <h1>Filter Data With Get Metohod using Json Result</h1>  
    37.         <p id="rDataT"></p>  
    38.         <style>  
    39.             table, th , td {  
    40.                 border: 1px solid grey;  
    41.                 border-collapse: collapse;  
    42.                 padding: 5px;  
    43.             }  
    44.             table tr:nth-child(odd) {  
    45.                 background-color: #f1f1f1;  
    46.             }  
    47.             table tr:nth-child(even) {  
    48.                 background-color: #ffffff;  
    49.             }  
    50.         </style>  
    51.         <p>  
    52. Enter Filter @Html.TextBox("Filter")  
    53.   
    54.             <input type="submit" id="GetCustomers" value="Submit"/>  
    55.         </p>  
    56.         <script type="text/jscript">  
    57.             $('#GetCustomers').click(function () {  
    58.                 $.getJSON('../Home/GetStudentList/' + $('#Filter').val(), function (data) {  
    59.                 var items = '  
    60.                 <table>  
    61.                     <tr>  
    62.                         <th>Student Name</th>  
    63.                         <th>Student Admission Number</th>  
    64.                     </tr>';  
    65.                     $.each(data, function (i, item) {  
    66.                         items += "  
    67.                         <tr>  
    68.                             <td>" + item.StdName + "</td>  
    69.                             <td>" + item.AdmNo + "</td>  
    70.                         </tr>";  
    71.                     });  
    72.                     items += "  
    73.                 </table>";  
    74.                 $('#rDataT').html(items);  
    75.             });  
    76.         })  
    77.   
    78.    </script>  
    79. -----------------------------------------------------------  
    80.   
    81.         <input id="btnGet" type="button" value="Get Data From List" />  
    82.         <div>  
    83.             <div id="ajaxDiv"></div>  
    84.         </div>  
    85.         <script type="text/javascript">  
    86.             $(document).ready(function () {  
    87.                 $('#btnGet').click(function () {  
    88.                     $.getJSON("../Home/GetJsonData"null, function (data) {  
    89.                         var div = $('#ajaxDiv');  
    90.                         div.html("  
    91.                         <br/> " + "Fetch from json Static List: " + "  
    92.                         <br/>");  
    93.                         $.each(data, function (i, item) {  
    94.                             printPerson(div, item);  
    95.                         });  
    96.                     });  
    97.                 });  
    98.             });  
    99.             function printPerson(div, item) {  
    100.                 var tbl = "";  
    101.                 div.append("  
    102.                 <br/>" + "FName: " + item.FirstName + ", LName: " + item.LastName);  
    103.                 $.each(item.Addresses, function (i, addr) {  
    104.                     printAddress(div, addr);  
    105.                 });  
    106.             }  
    107.             function printAddress(div, item) {  
    108.                 div.append("  
    109.                 <br/>" + " " + "Address: " + item.currentAddress);  
    110.             }  
    111.   
    112.         </script>  
    113.     </body>  
    114. </html>  
    And the Controller class Look like:
    1. namespace jQuery_Ajax_GET_POST_MVC.Controllers {  
    2.     public class HomeController: Controller {  
    3.         //  
    4.         // GET: /Home/  
    5.         public ActionResult FormGet() {  
    6.             return View();  
    7.         }  
    8.         public string InputMessage(string input) {  
    9.             if (!String.IsNullOrEmpty(input)) return "TextBox Value is =====> " + input + ".";  
    10.             else return "Please enter your name.";  
    11.         }  
    12.         public JsonResult GetStudentList(string id) {  
    13.             DataClasses1DataContext db = new DataClasses1DataContext();  
    14.             var result = from r in db.StudentMasters  
    15.             where r.StdName.StartsWith(id)  
    16.             select new {  
    17.                 r.StdName, r.AdmNo  
    18.             };  
    19.             return Json(result, JsonRequestBehavior.AllowGet);  
    20.         }  
    21.         public JsonResult GetJsonData() {  
    22.             var persons = new List < Person > {  
    23.                 new Person {  
    24.                     Id = 1, FirstName = "Jayant",  
    25.                     LastName = "Tripathy",  
    26.                     Addresses = new List < Address > {  
    27.                         new Address {  
    28.                             currentAddress = "xyz"  
    29.                         },  
    30.                     }  
    31.                 },  
    32.                 new Person {  
    33.                     Id = 2, FirstName = "Sri",  
    34.                     LastName = "Alex",  
    35.                     Addresses = new List < Address > {  
    36.                         new Address {  
    37.                             currentAddress = "Delhi"  
    38.                         },  
    39.                     }  
    40.                 }  
    41.             };  
    42.             return Json(persons, JsonRequestBehavior.AllowGet);  
    43.         }  
    44.     }  
    45.     public class Person {  
    46.         public int Id {  
    47.             get;  
    48.             set;  
    49.         }  
    50.         public string FirstName {  
    51.             get;  
    52.             set;  
    53.         }  
    54.         public string LastName {  
    55.             get;  
    56.             set;  
    57.         }  
    58.         public List < Address > Addresses {  
    59.             get;  
    60.             set;  
    61.         }  
    62.     }  
    63.     public class Address {  
    64.         public string currentAddress {  
    65.             get;  
    66.             set;  
    67.         }  
    68.     }  
    69. }  

The output looks like for 3 result is:

code output

POST Method Call

The .cshtml page like below:

  1. @{  
  2. ViewBag.Title = "FormPost";  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6. <html>  
  7.     <head>  
  8.         <meta name="viewport" content="width=device-width" />  
  9.         <title>FormGet</title>  
  10.         <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"  
  11. rel="stylesheet" type="text/css"/>  
  12.         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>  
  13.     </head>  
  14.     <h2>FormPost</h2>  
  15.     <p>  
  16. Enter your First name  
  17.   
  18.         <br />  
  19. @Html.TextBox("FirstName")  
  20.   
  21.     </p>  
  22.     <p>  
  23. Enter your Last name  
  24.   
  25.         <br />  
  26. @Html.TextBox("LastName")  
  27.   
  28.     </p>  
  29.     <input type="button" value="Save" id="Save" />  
  30.     <span id="msg" style="color:red;"/>  
  31.     <script type="text/javascript">  
  32.         $(document).ready(function () {  
  33.             $('#Save').click(function () {  
  34.                 var url = "../Home/PostForm";  
  35.                 var FirstName = $("#FirstName").val();  
  36.                 var LastName = $("#LastName").val();  
  37.                 $.post(url, { FirstName: FirstName, LastName: LastName }, function (data) {  
  38.                      $("#msg").html(data);  
  39.                 });  
  40.             })  
  41.         });  
  42.     </script>  
  43. </html>  
And the Controller class alike:
  1. public ActionResult FormPost() {  
  2.     return View();  
  3. }  
  4. [HttpPost]  
  5. public string PostForm(string FirstName, string LastName) {  
  6.     if (!String.IsNullOrEmpty(FirstName) && !String.IsNullOrEmpty(LastName)) {  
  7.         //You can coding here to save the data from dtabase here  
  8.         // I just use for return the meassge only !  
  9.         return "Thank you " + FirstName + " " + LastName + ". Record Saved.";  
  10.     } else {  
  11.         return "Please input valid details";  
  12.     }  
  13. }  
The Output of Post Method is:

output

 

Ebook Download
View all
Learn
View all