A Tip For Ajax Developers in ASP.Net MVC Framework

Introduction

This is another quick article for the ASP.NET developers, who're using Ajax (or will use the Ajax in their applications for async calls for the data to the server), and might be getting confused in the View-part of the MVC pattern. This article attempts to provide a tip for them with a simple method for creating Ajax functionality in their applications and how to get the confusion about View-part clear. The background to this article is a question that arose, of how to use the Ajax to get the data in the ASP.NET MVC framework. Although that was a simple task, I know new developers get into trouble in making the logic. That is why I am writing this article, to explain the core-concept of the behavior.

I will also be providing sample code that you can download and test in your application. This application would be a simple “Hello world, using Ajax in ASP.NET MVC” application. You can then make this application as complex as you require.

Getting hands dirty in some ASP.NET code

The first stage would be to write the back-end code for the application that is the ASP.NET MVC application. Wait, the first thing I want to elaborate on here is that Ajax requests don't usually require you to send an entire HTML markup, to be rendered. Usually, Ajax requests are used to download just a few details about the user, such as their name, their company name, or a little message such as a success message that the process user has started. That is why, sending an entire HTML markup would take somuch time and network size, by sending the entire XML tree as HTML markup.

That is why, I will not-create any View in this project. But I will work with just a single controller. That controller will be used to do all the actions and after the controller has been made, I will use the Route mechanism to allow custom URLs in the application that do not map to our actual HTML files on the application set up. Don't worry, as the application is built up, the concept of this paragraph will grow and you will understand better how I did it and what you will do to create your own Ajax running ASP.NET MVC application.

Note: If you're unaware of the ASP.NET MVC framework itself, I urge you to please go and read my other article that focuses on the ASP.NET MVC framework itself. In this article, I will not explain any concept about the framework itself, instead I will just simply mix things up and explain the Ajax and ASP.NET MVC part. So, it would be better if you move on to that article and first understand the underlying concepts about Model, View and Controller (that makes up the MVC part of the ASP.NET MVC framework).

First of all, let us create a controller. To create a controller, you can get some help from Visual Studio. Click on the Controllers folder and Add Controller to it. Name it to whatsoever you want to. I named it AjaxController to specify that it would control all of the Ajax requests over HTTP protocol. Once that has been done, you can create your own action methods that would respond to your own personal functions. I didn't bother creating any complex task, instead I just simply created a function, named “CustomAction”. It will be used as the URL of our Ajax handling web page.

Inside that page, you will rovide the following code, to handle it and provide the result to it. Like a simple C# application, the functions can have any return data type and thus, in an ASP.NET MVC application we can, instead of a View, return a string (or any other data type object) that would be sent down to the client as the response to his Ajax request. It would be much simpler and much shorter in structure.

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace AjaxRequests_in_ASPNET_MVC.Controllers  
  8. {  
  9.    public class AjaxController : Controller  
  10.    {  
  11.       // GET: Ajax  
  12.       public string Index()  
  13.       {  
  14.          return "Not allowed";  
  15.       }  
  16.   
  17.       // Our custom action, URL would be /ajax/customaction  
  18.       public string CustomAction()  
  19.       {  
  20.          // We're going to return a string, not a view.  
  21.          return "Hello world, using Ajax in ASP.NET MVC application.";  
  22.       }  
  23.    }  
  24. }  

 

The preceding code would return a string that can be then used as a response and rendered into the HTML or done whatsoever with it.

Now let us change the routes to actually let the application run without having to use a web page that is a View inside the Ajax folder in our Views folder. Open the App_Start folder and inside there open the RouteConfig file and inside it. Write this new route.MapPath() function.

 

  1. // Create a new route, set the controller to "Ajax" and the remaining would be the Action  
  2. // Note that there are no Views in the Views folder to map to this location.  
  3. routes.MapRoute(  
  4.    name: "AjaxController",  
  5.    url: "Ajax/{action}",  
  6.    defaults: new {controller = "Ajax"}  
  7. );  

 

Now this code will create a routing scheme in your application and is able to let your application run without actually having to have a specific file at that location to run and handle the Ajax request. In the preceding code, I am using the URLs of the type “/ajax/customajax“. In this URL Ajax is a constant string value, used as a path and then the customajax would be the action of the controller. When this URL would be called, ASP.NET would execute the CustomAjax action of the controller and would return the string result inside the function.

Performing the Ajax code

The Ajax code for this project is simple jQuery code to create an async request to the server, to download some more data. But before I share the code for the ajax request, I would like you to make a few changes in the _Layout.cshtml file of the project. The change is to include the jQuery library in the project, so that in the web page you can use the jQuery (because we will be using that layout). Add this line of code to your HTML markup's <head> element.

 

  1. <script src="~/Scripts/jquery-1.10.2.js"></script>  

 

Now that the jQuery has been added to your HTML DOM, you can use this library in other pages that has this page set as their layouts, to use the jQuery syntax and other objects. I will be using the Ajax.

The following code depicts the code used for an example ajax request:

 

  1. $(document).ready(function () {  
  2.    $.ajax({  
  3.       // The URL  
  4.       url: "ajax/customaction",  
  5.       // If the request was successfull; which will be, if it is not successfull check for errors  
  6.       success: function (data) {  
  7.          // Alert the data; it would be "Hello world, using Ajax in ASP.NET MVC application."  
  8.         alert(data);  
  9.       }  
  10.    });  
  11. });  

 

Now once this code would run, it would try to make a call to the URL specified, in the preceding section we discussed how ASP.NET would handle that request using the routings and action methods and then would return a single string value. It would finally alert the user with the string that would be returned. That would be a single Ajax running application that would return a simple plain message to the user without any complex and large sized View.

Points of Interest

ASP.NET MVC framework can support the Ajax requests, just like any simple website would.

You can use the routings to define your own custom URLs. You can define the paths that you want to use and the controller or action patterns. You are not required to always have a view being returned to the user. Sometimes (if you want) you can also send any kind of data (that in turn would be serialized to a string for transmitting).

You can download the online sample from Dropbox.


Similar Articles