Click here to Skip to main content
15,881,803 members
Articles / Web Development / HTML

A Tip for Ajax Developers in ASP.NET MVC Framework

Rate me:
Please Sign up or sign in to vote.
4.36/5 (6 votes)
13 Feb 2015MIT6 min read 13.9K   7   2
This blog post shares a tip for Ajax developers in ASP.NET MVC framework.

This is another quick blog post for the ASP.NET developers, who’re using Ajax (or are going to use 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 blog post would try to tip them up with a simple method of creating Ajax functionality in their applications, and how to get the confusion about View-part clear. The background to this post is a question, that arose, of how to use the Ajax to get the data in 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 blog post, to explain the core-concept of the behaviour.

I will also be providing a 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 after that, make this application complex as per your own requirements.

Getting Hands Dirty in Some ASP.NET Code

The first stage would be to write the back-end code for our application, which is the ASP.NET MVC application. Wait, the first thing I want to elaborate here is that Ajax requests don’t usually require you to send the 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 success message for the process user has started. That is why, sending the entire HTML markup would take a lot of time, and network size, by sending the entire XML tree as HTML markup.

That is why, I am going to not-create any View in this project. But I am going to work with just a single Controller. That controller would be used to perform all of the actions, and after the controller has been made, I am going to use the Route mechanism to allow custom URLs in our application; which do not map to our actual HTML files on the application set up. Don’t worry, as the application would build up, the concept of this paragraph would start to get some gravity and you will understand how did I do it and what you would do in order to create your own Ajax running ASP.NET MVC application.

Note: If you’re unaware of the ASP.NET MVC framework itself, I force you to please go and read my other article that focuses on the ASP.NET MVC framework itself. In this blog post, I am not going to explain any concept about the framework itself, instead, I am just going to simply swap 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 Controller, View and Model (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, whatsoever you want to. I named it as 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 response to your own personal functions. I didn’t bother creating any complex task, instead I just simply created a function, named it as “CustomAction”. It would be used as the URL to our Ajax handling web page.

Inside that page, you would write the following code, to handle it and provide the result to it. Like simple C# application, the functions can have any return data type and thus, in 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.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AjaxRequests_in_ASPNET_MVC.Controllers
{
   public class AjaxController : Controller
   {
      // GET: Ajax
      public string Index()
      {
         return "Not allowed";
      }

      // Our custom action, URL would be /ajax/customaction
      public string CustomAction()
      {
         // We're going to return a string, not a view.
         return "Hello world, using Ajax in ASP.NET MVC application.";
      }
   }
}

The above code would return a string, that can be then used as a response and rendered into the HTML or done what-so-ever 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.

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

Now this code would 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 above 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 a 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 your 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.

JavaScript
<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 which has this page set as their layouts, to make use of the jQuery syntax and other objects. I will be using the Ajax.

The following code depicts the code used for an example Ajax request,

JavaScript
$(document).ready(function () {
   $.ajax({
      // The URL
      url: "ajax/customaction",
      // If the request was successful; which will be, if it is not successful check for errors
      success: function (data) {
         // Alert the data; it would be "Hello world, using Ajax in ASP.NET MVC application."
        alert(data);
      }
   });
});

Now once this code would run, it would try to make a call to the URL specified, in the above 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, which would return 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 (which in turn would be serialized to string for transmitting).

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
Pakistan Pakistan
Afzaal Ahmad Zeeshan is a computer programmer from Rabwah, Pakistan, currently living in The Netherlands, likes .NET Core and Node.js for regular everyday development. Afzaal Ahmad works at Adyen as a Developer Advocate.

He is an expert with Cloud, Mobile, and API development. Afzaal has experience with the Azure platform and likes to build cross-platform libraries/software with .NET Core. Afzaal is an Alibaba Cloud MVP, twice he has been awarded Microsoft MVP status for his community leadership in software development, four times CodeProject MVP status for technical writing and mentoring, and 4 times C# Corner MVP status in the same field.

Comments and Discussions

 
Questiongreat Pin
Ekona_Pikin13-Jun-15 2:57
Ekona_Pikin13-Jun-15 2:57 
AnswerRe: great Pin
Afzaal Ahmad Zeeshan13-Jun-15 4:18
professionalAfzaal Ahmad Zeeshan13-Jun-15 4:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.