Using the jQuery UI Library in a MVC 3 Application to Build a Dialog Form

Posted by ChrisD on Geeks with Blogs See other posts from Geeks with Blogs or by ChrisD
Published on Thu, 01 Dec 2011 02:29:36 GMT Indexed on 2011/12/01 9:53 UTC
Read the original article Hit count: 334

Filed under:

Using a simulated dialog window is a nice way to handle inline data editing. The jQuery UI has a UI widget for a dialog window that makes it easy to get up and running with it in your application. With the release of ASP.NET MVC 3, Microsoft included the jQuery UI scripts and files in the MVC 3 project templates for Visual Studio. With the release of the MVC 3 Tools Update, Microsoft implemented the inclusion of those with NuGet as packages. That means we can get up and running using the latest version of the jQuery UI with minimal effort. To the code! Another that might interested you about JQuery Mobile and ASP.NET MVC 3 with C#.

If you are starting with a new MVC 3 application and have the Tools Update then you are a NuGet update and a <link> and <script> tag away from adding the jQuery UI to your project. If you are using an existing MVC project you can still get the jQuery UI library added to your project via NuGet and then add the link and script tags. Assuming that you have pulled down the latest version (at the time of this publish it was 1.8.13) you can add the following link and script tags to your <head> tag:

< link href = "@Url.Content(" ~ / Content / themes / base / jquery . ui . all . css ")" rel = "Stylesheet" type = "text/css" />
< script src = "@Url.Content(" ~ / Scripts / jquery-ui-1 . 8 . 13 . min . js ")" type = "text/javascript" ></ script >

The jQuery UI library relies upon the CSS scripts and some image files to handle rendering of its widgets (you can choose a different theme or role your own if you like). Adding these to the stock _Layout.cshtml file results in the following markup:

<!DOCTYPE html>
< html >
< head >
    < meta charset = "utf-8" />
    < title > @ViewBag.Title </ title >
    < link href = "@Url.Content(" ~ / Content / Site . css ")" rel = "stylesheet" type = "text/css" />
    <link href="@Url.Content("~/Content/themes/base/jquery.ui.all.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 >
    < script src = "@Url.Content(" ~ / Scripts / jquery-ui-1 . 8 . 13 . min . js ")" type = "text/javascript" ></ script >
</ head >

< body >
    @RenderBody()
</ body >
</ html >

Our example will involve building a list of notes with an id, title and description. Each note can be edited and new notes can be added. The user will never have to leave the single page of notes to manage the note data. The add and edit forms will be delivered in a jQuery UI dialog widget and the note list content will get reloaded via an AJAX call after each change to the list.

To begin, we need to craft a model and a data management class. We will do this so we can simulate data storage and get a feel for the workflow of the user experience. The first class named Note will have properties to represent our data model.

namespace Website . Models
{
    public class Note
    {
        public int Id { get ; set ; }
        public string Title { get ; set ; }
        public string Body { get ; set ; }
    }
}

The second class named NoteManager will be used to set up our simulated data storage and provide methods for querying and updating the data. We will take a look at the class content as a whole and then walk through each method after.

using System . Collections . ObjectModel ;
using System . Linq ;
using System . Web ;

namespace Website . Models
{
    public class NoteManager
    {
        public Collection < Note > Notes
        {
            get
            {
                if ( HttpRuntime . Cache [ "Notes" ] == null )
                    this . loadInitialData ();
                return ( Collection < Note >) HttpRuntime . Cache [ "Notes" ];
            }
        }

        private void loadInitialData ()
        {
            var notes = new Collection < Note >();
            notes . Add ( new Note
                          {
                              Id = 1 ,
                              Title = "Set DVR for Sunday" ,
                              Body = "Don't forget to record Game of Thrones!"
                          });
            notes . Add ( new Note
                          {
                              Id = 2 ,
                              Title = "Read MVC article" ,
                              Body = "Check out the new iwantmymvc.com post"
                          });
            notes . Add ( new Note
                          {
                              Id = 3 ,
                              Title = "Pick up kid" ,
                              Body = "Daughter out of school at 1:30pm on Thursday. Don't forget!"
                          });
            notes . Add ( new Note
                          {
                              Id = 4 ,
                              Title = "Paint" ,
                              Body = "Finish the 2nd coat in the bathroom"
                          });
            HttpRuntime . Cache [ "Notes" ] = notes ;
        }

        public Collection < Note > GetAll ()
        {
            return Notes ;
        }

        public Note GetById ( int id )
        {
            return Notes . Where ( i => i . Id == id ). FirstOrDefault ();
        }

        public int Save ( Note item )
        {
            if ( item . Id <= 0 )
                return saveAsNew ( item );
            var existingNote = Notes . Where ( i => i . Id == item . Id ). FirstOrDefault ();
            existingNote . Title = item . Title ;
            existingNote . Body = item . Body ;
            return existingNote . Id ;
        }

        private int saveAsNew ( Note item )
        {
            item . Id = Notes . Count + 1 ;
            Notes . Add ( item );
            return item . Id ;
        }
    }
}

The class has a property named Notes that is read only and handles instantiating a collection of Note objects in the runtime cache if it doesn't exist, and then returns the collection from the cache. This property is there to give us a simulated storage so that we didn't have to add a full blown database (beyond the scope of this post). The private method loadInitialData handles pre-filling the collection of Note objects with some initial data and stuffs them into the cache. Both of these chunks of code would be refactored out with a move to a real means of data storage.

The GetAll and GetById methods access our simulated data storage to return all of our notes or a specific note by id. The Save method takes in a Note object, checks to see if it has an Id less than or equal to zero (we assume that an Id that is not greater than zero represents a note that is new) and if so, calls the private method saveAsNew . If the Note item sent in has an Id , the code finds that Note in the simulated storage, updates the Title and Description , and returns the Id value. The saveAsNew method sets the Id , adds it to the simulated storage, and returns the Id value. The increment of the Id is simulated here by getting the current count of the note collection and adding 1 to it. The setting of the Id is the only other chunk of code that would be refactored out when moving to a different data storage approach.

With our model and data manager code in place we can turn our attention to the controller and views. We can do all of our work in a single controller. If we use a HomeController , we can add an action method named Index that will return our main view. An action method named List will get all of our Note objects from our manager and return a partial view. We will use some jQuery to make an AJAX call to that action method and update our main view with the partial view content returned. Since the jQuery AJAX call will cache the call to the content in Internet Explorer by default (a setting in jQuery), we will decorate the List, Create and Edit action methods with the OutputCache attribute and a duration of 0. This will send the no-cache flag back in the header of the content to the browser and jQuery will pick that up and not cache the AJAX call.

The Create action method instantiates a new Note model object and returns a partial view, specifying the NoteForm.cshtml view file and passing in the model. The NoteForm view is used for the add and edit functionality. The Edit action method takes in the Id of the note to be edited, loads the Note model object based on that Id , and does the same return of the partial view as the Create method. The Save method takes in the posted Note object and sends it to the manager to save. It is decorated with the HttpPost attribute to ensure that it will only be available via a POST. It returns a Json object with a property named Success that can be used by the UX to verify everything went well (we won't use that in our example). Both the add and edit actions in the UX will post to the Save action method, allowing us to reduce the amount of unique jQuery we need to write in our view.

The contents of the HomeController.cs file:

using System . Web . Mvc ;
using Website . Models ;

namespace Website . Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index ()
        {
            return View ();
        }

        [ OutputCache ( Duration = 0 )]
        public ActionResult List ()
        {
            var manager = new NoteManager ();
            var model = manager . GetAll ();
            return PartialView ( model );
        }

        [ OutputCache ( Duration = 0 )]
        public ActionResult Create ()
        {
            var model = new Note ();
            return PartialView ( "NoteForm" , model );
        }

        [ OutputCache ( Duration = 0 )]
        public ActionResult Edit ( int id )
        {
            var manager = new NoteManager ();
            var model = manager . GetById ( id );
            return PartialView ( "NoteForm" , model );
        }

        [ HttpPost ]
        public JsonResult Save ( Note note )
        {
            var manager = new NoteManager ();
            var noteId = manager . Save ( note );
            return Json ( new { Success = noteId > 0 });
        }
    }
}

The view for the note form, NoteForm.cshtml , looks like so:

@model Website . Models . Note
@using ( Html . BeginForm ( "Save" , "Home" , FormMethod . Post , new { id = "NoteForm" })) {
@Html . Hidden ( "Id" )
< label class = "Title" >
    < span > Title < /span><br / >
    @Html . TextBox ( "Title" )
< /label>
<label class="Body">
    <span>Body</
span >< br />
    @Html . TextArea ( "Body" )
< /label>
}

It is a strongly typed view for our Note model class. We give the <form> element an id attribute so that we can reference it via jQuery. The <label> and <span> tags give our UX some structure that we can style with some CSS.

The List.cshtml view is used to render out a <ul> element with all of our notes.

@model IEnumerable < Website . Models . Note >
< ul
class = "NotesList" >
    @foreach (
var note in Model )
    {
    < li >
        @note .
Title < br />
        @note .
Body < br />
        < span
class = "EditLink ButtonLink" noteid = "@note.Id" > Edit < /span>
    </
li >
    }
<
/ul>

This view is strongly typed as well. It includes a <span> tag that we will use as an edit button. We add a custom attribute named noteid to the <span> tag that we can use in our jQuery to identify the Id of the note object we want to edit.

The view, Index.cshtml , contains a bit of html block structure and all of our jQuery logic code.

@ {
   
ViewBag . Title = "Index" ;
}
< h2 >
Notes < /h2>
<div id="NoteListBlock"></
div >
< span
class = "AddLink ButtonLink" > Add New Note < /span>
<div id="NoteDialog" title="" class="Hidden"></
div >
< script type =
"text/javascript" >
    $ (
function () {
        $ (
"#NoteDialog" ). dialog ({
            autoOpen :
false , width : 400 , height : 330 , modal : true ,
            buttons : {
               
"Save" : function () {
                    $ . post (
"/Home/Save" ,
                        $ (
"#NoteForm" ). serialize (),
                       
function () {
                            $ (
"#NoteDialog" ). dialog ( "close" );
                           
LoadList ();
                        });
                },
               
Cancel : function () { $ ( this ). dialog ( "close" ); }
            }
        });
        $ (
".EditLink" ). live ( "click" , function () {
           
var id = $ ( this ). attr ( "noteid" );
            $ (
"#NoteDialog" ). html ( "" )
                . dialog (
"option" , "title" , "Edit Note" )
                . load (
"/Home/Edit/" + id , function () { $ ( "#NoteDialog" ). dialog ( "open" ); });
        });
        $ (
".AddLink" ). click ( function () {
            $ (
"#NoteDialog" ). html ( "" )
                . dialog (
"option" , "title" , "Add Note" )
                . load (
"/Home/Create" , function () { $ ( "#NoteDialog" ). dialog ( "open" ); });
        });
       
LoadList ();
    });
   
function LoadList () {
        $ (
"#NoteListBlock" ). load ( "/Home/List" );
    }
<
/script>

The <div> tag with the id attribute of "NoteListBlock" is used as a container target for the load of the partial view content of our List action method. It starts out empty and will get loaded with content via jQuery once the DOM is loaded. The <div> tag with the id attribute of "NoteDialog" is the element for our dialog widget. The jQuery UI library will use the title attribute for the text in the dialog widget top header bar. We start out with it empty here and will dynamically change the text via jQuery based on the request to either add or edit a note. This <div> tag is given a CSS class named "Hidden" that will set the display:none style on the element. Since our call to the jQuery UI method to make the element a dialog widget will occur in the jQuery document ready code block, the end user will see the <div> element rendered in their browser as the page renders and then it will hide after that jQuery call. Adding the display:hidden to the <div> element via CSS will ensure that it is never rendered until the user triggers the request to open the dialog.

The jQuery document load block contains the setup for the dialog node, click event bindings for the edit and add links, and a call to a JavaScript function called LoadList that handles the AJAX call to the List action method. The .dialog() method is called on the "NoteDialog" <div> element and the options are set for the dialog widget. The buttons option defines 2 buttons and their click actions. The first is the "Save" button (the text in quotations is used as the text for the button) that will do an AJAX post to our Save action method and send the serialized form data from the note form (targeted with the id attribute "NoteForm"). Upon completion it will close the dialog widget and call the LoadList to update the UX without a redirect. The "Cancel" button simply closes the dialog widget.

The .live() method handles binding a function to the "click" event on all elements with the CSS class named EditLink . We use the .live() method because it will catch and bind our function to elements even as the DOM changes. Since we will be constantly changing the note list as we add and edit we want to ensure that the edit links get wired up with click events. The function for the click event on the edit links gets the noteid attribute and stores it in a local variable. Then it clears out the HTML in the dialog element (to ensure a fresh start), calls the .dialog() method and sets the "title" option (this sets the title attribute value), and then calls the .load() AJAX method to hit our Edit action method and inject the returned content into the "NoteDialog" <div> element. Once the .load() method is complete it opens the dialog widget.

The click event binding for the add link is similar to the edit, only we don't need to get the id value and we load the Create action method. This binding is done via the .click() method because it will only be bound on the initial load of the page. The add button will always exist.

Finally, we toss in some CSS in the Content/Site.css file to style our form and the add/edit links.

. ButtonLink { color : Blue ; cursor : pointer ; }
. ButtonLink : hover { text - decoration : underline ; }
. Hidden { display : none ; }
#NoteForm label { display:block; margin-bottom:6px; }
#NoteForm label > span { font-weight:bold; }
#NoteForm input[type=text] { width:350px; }
#NoteForm textarea { width:350px; height:80px; }

With all of our code in place we can do an F5 and see our list of notes:

If we click on an edit link we will get the dialog widget with the correct note data loaded:

And if we click on the add new note link we will get the dialog widget with the empty form:

The end result of our solution tree for our sample:

© Geeks with Blogs or respective owner