Ajax in ASP.Net MVC 3

In asp.net web form application, if we need ajax service, we will need to create wcf services on server side to serve ajax calls, while in MVC web application(version 3), no wcf is needed, a controller will do.

Here are two examples (GET and POST) of how to use ajax in mvc application

Http Get example: ajax consumer in view

<script type="text/javascript">
  var user = {
                'id': 1
            };

    $.get(
                'home/getUser',
                user,
                function (data) {
                    alert(data.name);
                }

    );
</script>

Http Get example: ajax server in home controller

public class HomeController : Controller
{
	// data GET service
     public JsonResult getUser(int id)
     {
            
            User user = db.Users.where(u=>u.id==id)

            return Json(user,JsonRequestBehavior.AllowGet);
     }

}

A few points:

Controller must return JsonResult rather than ActionResult as a normal controller does as we would want the data to be returnd as json data, and it does not have a ‘d’ wrapper

JsonRequestBehavior.AllowGet must be set in Json()call, otherwise you will get:

500 internal server error with message like

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet

You only need to set this parameter for GET and returning JSON array to avoid JSON hijacking, no need for POST requests.
Http POST example: ajax consumer in view

<script type="text/javascript">
var user={
            'name':’TheUser’,
            'age':30
        };

 $.post(
            'home/SaveUser',
            user,
            function (data) {
                if (data === true) {
		           alert('User is saved');     
                }
                else {
                   
                    alert('Failed to save the user');
 
                }
            },
            'json'
        );
</script>

Http POST example: ajax server in home controller

public class HomeController : Controller
{
	// data POST service
  [AcceptVerbs(HttpVerbs.Post)]
   public JsonResult SaveUser (string name, int age)
   {
            
        return Json(true);
    }
}

A few points:

Have to decorate the controller with ‘POST’

Datatype in $.post in example is set to json, but it is not necessary to be so, if you just pass data in fields rather than in complex object. When it is not set to json it will use application/x-www-form-urlencoded as a way to pass data in standard post.

Summary:
In asp.net MVC you can use controller as ajax server without having to use wcf, compared with wcf, no configuration is needed.

Tags:

This entry was posted on Friday, March 25th, 2011 at 1:22 am and is filed under ASP.NET. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

12 Responses to “Ajax in ASP.Net MVC 3”

  1. John says:

    Thanks for the Tutorial, this example was exactly what I was looking for.

  2. y2kstephen says:

    Thanks a lot!

  3. MattW says:

    Thanks for the article!!

  4. Carl says:

    Excellent, thanks.

  5. asp.net, c#,javascript…

    [...]Ajax in ASP.Net MVC 3 | CleanCode NZ[...]…

  6. Nice illustration, but i’m little doubtful if the newbies would be able to develop a sample ASP website or a web app just with that :) But, must say your site indeed has clean codes like the name suggests!

  7. Shrinivas says:

    I am new to mvc3 and i tried implementing the same concept of GET in my new mvc3 project. I doesnt see any call to the action method in controller. Can you please upload the complete project else please let me know wich version of jquery you are using in your project. I am using 1.5.1 in my project which comes as default.

    • CleanCodeNZ says:

      Hi Shrinivas:
      I am sorry that I have not got the original code with me, and version of jquery does not matter here I believe. just be careful that the url you gave to ajax jquery is accurate. you can also test your url out of context like in a browser.

  8. Nguyen Duc Anh says:

    thankyou!

  9. S.Prabhakar says:

    If you could have added some view side (aspx or cshtml) code to the tutorial that would be more helpful.
    I am using a typical MVC cshtml view that has multiple forms to be posted.
    I wanted to convert them into ajax call and looking for this tutorial any samples that would help me.
    Anyway nice article.
    thanks.

    • CleanCodeNZ says:

      Hi there: the ajax calls are fired in javascript, just embed the javascripts in the example in your views, it has nothing to do with Form, that is the point of ajax, moving your old form actions into ajax calls really suits your task. Cheers

Leave a Reply

*