AJAX Using RESTful MVC3 Services and jQuery

REST is an approach to providing a highly efficient API that can be called by other applications or by your AJAX framework. MVC3 makes it easy to define REST services in your controllers to be called by jQuery AJAX requests in your view.

Why REST?

Web Services were great when they came out but the problems in web services quickly became apparent. Web Services have a fairly large overhead in terms of all of the additional XML that the protocol itself requires. Also the protocol was so complicated that it wasn't realistic to expect developers to be able to access a web service without automated tools to automatically generate all of the stubs and to handle the complexity of the protocol.

RESTful services started becoming in vogue a few years ago riding high on strong support from Google and satisfying a broad developer need for a simpler way to access remote services. Each RESTful service has a separate URL that can optionally support different functionality depending on the type of HTTP Request. For example, an HTTP GET request to /Boat would return a Boat object, while a POST request to the same URL could save the object and an HTTP DELETE request to the same URL could delete the Boat.

Defining Your Methods

Creating a RESTful method that is AJAX callable in MVC3 could not possibly be any simpler, thanks to major advances made in the framework's object serializing/deserialization capabilities. Just define an action on your controller that returns JsonResult and use the Json helper to turn your object into a serialized JsonResult.

public JsonResult GetBoat(int BoatID)
{
//Get a boat from the database...
Boat b = new Boat();
b.BoatID = BoatID;
return Json(b);
}

Passing objects back up to the server is easier than MVC2. MVC2 required a combination of magic, voodoo and extensive configuration. In MVC3, as long as the object you create on the client has the same names as the properties on your server side object, MVC3 will convert that client side javascript object into your server side object.

public JsonResult SetBoat(Boat b)
{
//Save the Boat b
return Json("OK");
}

Allow Get

A GET request passes the parameters in the URL of the request. When a get request is made, the data passed in the URL of the GET request is viewable by 3rd parties on the internet even over an HTTPS connection.B The returned data inside of the body of the response is protected by HTTP, but the URL parameter you passed in the query string is not.

With this in mind, you have to be very careful to insure you're not passing anything in the GET request that you wouldn't want being intercepted. If you do choose to allow a GET request, you have to set JsonRequestBehavior.Get to the Json helper for your return value to let ASP.NET MVC3 know you're aware of the risk you're taking and making an explicit opt-in to say you know you're not passing anything secret.

return Json(b, JsonRequestBehavior.AllowGet);

Calling Your RESTful AJAX Methods from jQuery

jQuery has a few different methods to make AJAX calls, but the $.ajax method itself covers all the bases you'd practically need.

You can create your Boat object in JavaScript without having to make it a special object in any way other than to have the same public properties as your server side object.

var boat = {'BoatID':123,
'BoatName':'Titanic','Captain':'Leo',
'CaptainSaltinessPercent':25};

To post data to an MVC3 Rest service with an object as it's parameter, the jQuery ajax method supports the following properties:

  • url - The URL of the service to call, can be a relative path to the current view.
  • type - To send an object up to the server, POST is highly recommended.
  • contentType - This is the mime type to be posted. For MVC3 services that take objects as a parameter, application/json is recommended.
  • dataType - Setting dataType as JSON lets jQuery know that we are planning on sending a JSON string representing our object up to the server.
  • data - This parameter is the actual data to send. Use the helper method JSON.stringify to convert your client side object into a JSON string.
  • success - Defines the client side function to call if the server side method returns successfully.
  • error - Defines the client side function to call if there was an error running your method. It is wise to always define an error handler because due to the nature of the internet, things fail sometimes even under the best conditions.
$.ajax({
url: "/MyBoat",
type:"POST",
contentType:"application/json",
dataType:"JSON",
data:JSON.stringify(myBoat),
success: function(){
alert("Saved successfully!");
},
B B B B B B  error:function(msg) { alert("Error saving:"+ msg); }
});

Conclusion

MVC3 is a huge step forward in enhancing the synergistic relationship between client code and server code. Objects now pass much more easily from server to client and back again without requiring additional plumbing or exotic tricks.



Related Articles

Comments

  • Cheap Oakley Jawbone sale online

    Posted by kubejwiui on 07/01/2013 08:52pm

    Sale Ray Bans ,At all times more popular as the most influential design company, It can be little wonder you will find rows of Hollywood and the fashion industry called 'Oakley, legendary fashion icon, the initial in 1973 in Milan, the devil is going to be available to wear Austrian Cleveland. Today, beyond the bright colors and unusual shapes of persistent organic pollutants, the more eye-catching picture of stylish glasses tend to be defined than ever before. Fake Oakleys ,Oakley sunglasses will be impressive, and along with a definite overall appearance turned out to run translates to the person you selected a home based business as a new sort of wind. Probably the most demanding sport professionals in the world contributed towards the Oakley Sunglasses30 years of innovation. The athletes have won more championships and medals of our own sunglasses than you are on Earth every other single sport product. OakLey FueL CeLL SungLasses ,Generally inside the lens design of Oakley sunglasses sale, or a greater various colors inside fashion choice, more high-level, there are a lot of female friends choose to wear employed to match the contour of Oakley sunglasses. You may find a distinct fashionable and classy sunglasses, and if so, you'll be glad to find out that the web shop is best destination to find designer sunglasses. The border from the straight distinct Oakley sunglasses, will assist balance the sensation of vertical see your face shape, even if it is just a broad forehead and narrow chin. Sun block lotion is frequently determined to not simply understand that you've got already installed an increasingly stylish and more attractive appearance, which can be actually a powerful way to. You may use in biochemistry Labrador, together with wood processing. They might be working at the snow track and field, plus in swimming. Note can not see ultraviolet, the appliance Oakley sunscreen, to reduce the sun's ultraviolet radiation power, especially, is more harmful UV, speaks. Oakley is you expect from the whole world of performance innovation producing unparalleled technology products, it utilizes a unique interchangeable lens design, and that means you obtain the product with the optical properties of the match along with the environment. Addition, plutonite contacts provides a many ultra-violet sun sun's rays 100% protection, and special protection of influence. Oakley sunglasses (female) benefits from its special history, almost all of them wanting to imitate them. Not many women simply get the glasses, they find what they need. Oakley sunglasses, you may pick a qualified sunglasses, Oakley sunglasses popular Oakley sunglasses sell on this planet.

    Reply
  • Sr Web Developer

    Posted by Michael Wassernann on 04/15/2013 01:49pm

    Nicely done, with out clutter.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Managing your company's financials is the backbone of your business and is vital to the long-term health and viability of your company. To continue applying the necessary financial rigor to support rapid growth, the accounting department needs the right tools to most efficiently do their job. Read this white paper to understand the 10 essentials of a complete financial management system and how the right solution can help you keep up with the rapidly changing business world.

  • Hybrid cloud platforms need to think in terms of sweet spots when it comes to application platform interface (API) integration. Cloud Velocity has taken a unique approach to tight integration with the API sweet spot; enough to support the agility of physical and virtual apps, including multi-tier environments and databases, while reducing capital and operating costs. Read this case study to learn how a global-level Fortune 1000 company was able to deploy an entire 6+ TB Oracle eCommerce stack in Amazon Web …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds