Simple MVC AJAX GET Method

MVC makes doing AJAX calls simple.  As I have said before, I do not like the AJAX controls and methods that the Microsoft ships with the MVC platform.  I prefer to create my own AJAX methods instead of posting a AJAX form.  I find I can get better control and I can create tighter rules around elements of importance.

The one thing I learned early is when doing a Get Method, you need to ensure that you give permission to the AJAX call to return JSON by adding the following to your JSON return object:

JsonRequestBehavior.AllowGet

This is an easy example of how to use your basic jQuery with your MVC Controller.

This is my view:

 @{  
   Layout = null;  
 }  
   
 <!DOCTYPE html>  
   
 <html>  
 <head>  
   <meta name="viewport" content="width=device-width" />  
   <title>Test</title>  
   <script src="~/Scripts/jquery-1.8.2.js"></script>  
 </head>  
 <body>  
   <div>  
     <label for="txtName">Name: </label><input type="text" id="txtName" />  
     <button id="btnSayHello" value="SayHello">Say Hello</button>  
     <br />  
     <label id="lblMessage"></label>  
   </div>  
   
   <script type="text/javascript">  
     var $SayHelloURL = "@Url.Action("SayHello", "Home")";  
     $("#btnSayHello").on("click", function () {  
       var _name = $("#txtName").val();  
       $.ajax({  
         method: "GET",  
         url: $SayHelloURL,  
         data: { name: _name },  
         success: function(data){  
           if(data.Success)  
           {  
             $("#lblMessage").html(data.Message);  
             $("#txtName").val('');  
           } else {  
             $("#lblMessage").html(data.Message);  
             $("#txtName").focus();  
           }  
         }  
       });  
     });  
   </script>  
 </body>  
 </html>  

This is my controller:

1:  using System;  
2:  using System.Collections.Generic;  
3:  using System.Linq;  
4:  using System.Web;  
5:  using System.Web.Mvc;  
6:    
7:  namespace TestProject.Controllers  
8:  {  
9:    public class HomeController : Controller  
10:    {  
11:      [HttpGet]  
12:      public JsonResult SayHello(String name)  
13:      {  
14:        Dictionary<String,object> aryOfDictionary = new Dictionary<string,object>();  
15:        if(name.Length > 0)  
16:        {  
17:          aryOfDictionary.Add("Succes", true);  
18:          aryOfDictionary.Add("Message", @"<span style=""color:Blue;"">Hello " + name + ".</span>");  
19:        }  
20:        else  
21:        {  
22:          aryOfDictionary.Add("Succes", false);  
23:          aryOfDictionary.Add("Message", @"<span style=""color:Red;"">Please Enter Your Name...</span>");  
24:        }  
25:        return Json(aryOfDictionary, JsonRequestBehavior.AllowGet);  
26:      }  
27:    
28:      public ActionResult Test()  
29:      {  
30:         return View();  
31:      }  
32:    }  
33:  }  
34:    

Andrew Pallant (@LdnDeveloper) has been a web, database and desktop developer for over 16 years. Andrew has worked on projects that ranged from factory automation to writing business applications. Most recently he has been heavily involved in various forms for ecommerce projects. Over the years Andrew has worn many hats: Project Manager, IT Manager, Lead Developer, Supervisor of Developers and many more - See more at: http://www.unlatched.com/#sthash.8DiTkpKy.dpuf

Posted in DotNet, How To, jQuery, JSON, Web