Using jQuery in ASP.NET applications – part 2 MVC

This is the second post in the “Using jQuery in ASP.NET applications” series where we tackle the how you can access your code base with a jQuery ajax call.

Setting up the project

Open up Visual Studio and create a new ASP.NET MVC 3 Web Application

Enter a name and a location and click the OK button. Visual Studio will now ask you if you want to create an empty, an intranet or an Internet application. Let’s choose the last one. For the view engine choose Razor. We don’t need any unit tests in this demo so leave the “create a unit test project” unchecked and click the OK button.

Visual Studio will now create a standard MVC web project where jQuery and Modernizer are included. When our project is created it will look like this:

We will reuse the simple demo application we created in the previous blog post that will let a user add his favorite book title to his wish list.

Alter the default view

Like in the Web Forms application we’ll alter the default view Visual Studio created for us. Open up the solution explorer and go to the Home folder in the Views folder. Double click Index.cshtml file. Remove the default message and add a textbox, a button and a listbox so our view looks like:

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<input name="BookTitle" id="txtBookTitle" />
<input type="button" id="btnAddBookTitle" value="Add book title"><br/>
<select id="lstBookTitles" name="lsstBookTitles" size="4"></select>

Hit run (F5) in Visual Studio and our fabulous designed application will open up in a browser. As mentioned before, the focus is this post is the implementation of the ajax call, not the design of the application.

Add our business object

In our application we’re going to use a class to exchange data from the server to the client in the ajax call. Open up the solution explorer and right click on the Models folder and choose Add => Class. Name the class Book and add the following properties so our class looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Demo.Models
{
    public class Book
    {
        public long BookId { get; set; }
        public string BookTitle { get; set; }
    }
}

Reference and create javascript files

Unlike in Web Forms, a MVC application has default a reference to the jQuery javascript file. In solution explorer open up the Shared folder in the Views folder. There you’ll find a _Layout.cshtml class. This class is more or less the MasterPage for a MVC application. In the head tag you’ll already find a reference to the jQuery-$version$.min.js file. We don’t want to include our custom javascript in the view as it then will be loaded in every screen of our application. This is first unnecessary and secondly will slow down the page as he has to load multiple sources from the server. In MVC you can create a section in the master view. In your “child” view you can refer to that section to add custom scripts our styles into the page. Add the @RenderSection helper in the head block of the _Layout.cshtml view as shown below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    @RenderSection("JavaScript", required: false)
</head>
<body>
.....

Create our custom javascript file

In solution explorer right click on the Scripts folder and choose Add => New Item. In the window that will appear select Jscript file, name it Home.js and click the Add button.

Reference our custom javascript file in our view

We still have to create a reference to our custom created Home.js file in our view. Open up the index.cshtml again and add the section tag at the top of the view. In that section add a reference to the Home.js file.

@section JavaScript
{
    <script src="../../Scripts/Home.js" type="text/javascript"></script>
}
@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<input name="BookTitle" id="txtBookTitle" />
<input type="button" id="btnAddBookTitle" value="Add book title"><br/>
<select id="lstBookTitles" name="lsstBookTitles" size="4"></select>

Hit Run (F5) again in Visual Studio and our page should still look the same.

Create the Ajax Method in the controller

In MVC adding a ajax method is as simple as adding an action in our controller. Instead of returning a View we’ll return a JsonResult that will convert our .NET book class to a Json representation.

private static string sessionName = "BooksSessionName";

public ActionResult AddBook(string bookTitle)
{
	List<Book> books;
	if (Session[sessionName] != null)
	{
		books = Session[sessionName] as List<Book>;
		if (books == null)
			books = new List<Book>();
	}
	else
	{
		books = new List<Book>();
	}
	Book book = new Book() { BookId = GetNextBookTitleId(), BookTitle = bookTitle };
	books.Add(book);
	Session[sessionName] = books;
	return Json(book,JsonRequestBehavior.AllowGet);
}

private long GetNextBookTitleId()
{
	if (Session[sessionName] != null)
	{
		List<Book> books = Session[sessionName] as List<Book>;
		if (books != null)
		{
			long ticket = books.Max(t => t.BookId);
			ticket++;
			return ticket;
		}
	}
	return 1;
}

I’ve added a static string to hold the session name and a private helper method to generate an id for the added book based on the list in the session. In the return statement we create the Json object we want to send to the client. Don’t forget the JsonRequestBehavior.AllowGet flag to allow GET requests to this method!

Create the Ajax call in jQuery

Now our code behind method is available we only deed to call this method from the client. When the button is clicked we’ll call the method and add the returned object to our list. Let’s start with creating an event handler for the click event on the button. Open up the Home.js file we created and add the following lines:

$(document).ready(function () {
    $("#btnAddBookTitle").click(function () {
        alert('Button is clicked !!');
        return false;
    });
});

If we now run our application (hit Run in VS or F5) and we press the ‘Add book tile ‘ button well see a javascript popup telling we’ve clicked the button. Now we can add the ajax implementation.

$(document).ready(function () {
    $("#btnAddBookTitle").click(function () {
        var $bookTitle = $("#txtBookTitle").val();
        $.ajax({
            type: "GET",
            url: "/Home/AddBook/",
            data: {bookTitle:$bookTitle},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
            },
            error: function () {
                alert('Error calling AddBook');
            }
        });
        return false;
    });
});

I’ve added a variable $bookTitle that holds the value the user has entered in the text box. After that line we’ll start the ajax call. I’ve added some settings in that call:

  • Type: can be POST or GET, in this case: GET
  • url: The url where the values should be posted to: the controller name + action name
  • The data: we have to send the booktitle to our code behind method. This we will rap in a JSON format (more info on http://www.json.org)
  • ContentType: We declare we want to use JSON to communicate with the server
  • Datatype: We declare we want to use JSON to receive data from the server
  • Success: what we have to do when the call is succeeded (not filled out yet)
  • Error: what we have to do when the call throws an error.(alerting a message box in this case)

If we run the application and open up a Firebug screen (in Internet explorer you can use the Developer Tools as you can use these in the Chrome browser). After clicking the button we see a async request to the server that returns an JSON object representing our book.

Implement success function

All we now have to do is to implement the success function so our returned book is added to the list of book titles.

$(document).ready(function () {
    $("#btnAddBookTitle").click(function () {
        var $bookTitle = $("#txtBookTitle").val();
        $.ajax({
            type: "GET",
            url: "/Home/AddBook/",
            data: {bookTitle:$bookTitle},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var $book = msg;
                var $option = new Option($book.BookTitle, $book.BookId);
                $("#lstBookTitles").append($option);
            },
            error: function () {
                alert('Error calling AddBook');
            }
        });
        return false;
    });
});

As we’re receiving an javascript object (JSON) we can create the option using the parameters of the object.

If your un the application now you’ll see the book titles are added to the list, all with their id. From here you can implement delete, edit and other functions.

Next post will be how we can refactor the above so we create an API that’s not tied to a specific controller.

 

Leave a Reply

Your email address will not be published. Required fields are marked *