Thursday, July 08, 2010

@ElijahManor is Looking for a jQuery &| ASP.NET MVC Job

If you haven’t heard already, I am looking for a new job opportunity… and yes, I realize the title of this blog is speaking in the 3rd person ;)

I am primarily looking for a full-time position where I can either work in a Nashville office or work remotely from Nashville.

I am a Microsoft MVP of ASP.NET and a member of the ASPInsiders group.

I specialize in developing with jQuery and ASP.NET MVC. I tend to focus on the UI only (everything up to the web service call to the middle tier).

I enjoy blogging, writing technical articles, speaking, and playing with the latest and greatest web development tools and libraries.

You can find my resume on my LinkedIn profile.

I look forward to hearing more about your company & the positions that you have available.

Please contact me either through LinkedIn, Twitter (@elijahmanor), or my Contact page.

Thursday, July 01, 2010

jQuery jqGrid Plugin: Add, Edit, Delete with ASP.NET MVC

 

Introduction

There are a lot of articles out there that show you how to integrate with the jQuery jqGrid Plugin from a listing, paging, sorting approach, but I haven’t seen many that show the integration with the add/edit/delete features that jqGrid offers.

It turns out that it isn’t very difficult to do, but it took quite a bit of digging in the jqGrid API documentation for me to find all the things I needed.

The following article will show how to customize the add/edit/delete modal experience inside of the jqGrid with ASP.NET MVC.

Contact ViewModel

First, you start off with your ViewModel. In this case the following is really bare bones. I haven’t annotated the properties with metadata because I actually do that manually in the jqGrid columns. That isn’t optimal, but it would be nice to have these automatically mapped. That sounds like another blog post ;)

public class ContactViewModel
{
    public System.Guid ContactId { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public string PhoneNumber { get; set; }

    public DateTime DateOfBirth { get; set; }

    public bool IsMarried { get; set; }
}

Contact View

The following code setups up the jqGrid to support add, edit, and delete.

The first function you’ll see is a custom validator that checks to see if the phone number has a length of 14. Yes, it isn’t bullet-proof validation by any stretch of the imagination, but its more of an example of what can be done.

Next you’ll see the updateDialog object literal defining the look and behavior of the add, edit, and delete dialog windows. The main property to define is the URL where the AJAX requests will post the data. You can also control whether the dialog closes immediately, if it’s a modal dialog, etc…

The next important thing to notice is the “key: true” property of the ContactId column. If you don’t set this property then the POST for the delete command  only send the relative ID that jqGrid generates, not the ContactId that you need. So, this is important ;)

Note: You’ll see some code below setting global properties for the jqGrid such as the title of the dialogs, buttons, etc. If you don’t do this then you’ll get generic titles. I figured these customizations made the user experience a little nicer, but things will work just find without them.

function isValidPhone(value, name) {
    console.log('isValidPhone');
    var errorMessage = name + ': Invalid Format';
    var success = value.length === 14;
    return [success, success ? '' : errorMessage];
}  

$(document).ready(function () {
    var updateDialog = {
        url: '<%= Url.Action("Update", "Contact") %>'
        , closeAfterAdd: true
        , closeAfterEdit: true
        , afterShowForm: function (formId) {
            $("#PhoneNumber").mask("(999) 999-9999");
            $("#DateOfBirth").datepicker();
        }
        , afterclickPgButtons: function (whichbutton, formid, rowid) {
            $("#PhoneNumber").mask("(999) 999-9999");
        }
        , modal: true
        , width: "400"
    };

    $.jgrid.nav.addtext = "Add";
    $.jgrid.nav.edittext = "Edit";
    $.jgrid.nav.deltext = "Delete";
    $.jgrid.edit.addCaption = "Add Contact";
    $.jgrid.edit.editCaption = "Edit Contact";
    $.jgrid.del.caption = "Delete Contact";
    $.jgrid.del.msg = "Delete selected Contact?";

    $("#list").jqGrid({
        url: '<%= Url.Action("List", "Contact") %>',
        datatype: 'json',
        mtype: 'GET',
        colNames: ['ContactId', 'Name', 'Date of Birth', 'E-mail', 'Phone Number', 'Married'],
        colModel: [
            { name: 'ContactId', index: 'ContactId', width: 40, align: 'left', key: true, editable: true, editrules: { edithidden: false }, hidedlg: true, hidden: true },
            { name: 'Name', index: 'Name', width: 300, align: 'left', editable: true, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} },
            { name: 'DateOfBirth', index: 'DateOfBirth', width: 200, align: 'left', formatter: 'date', datefmt: 'm/d/Y', editable: true, edittype: 'text', editrules: { required: true, date: true }, formoptions: { elmsuffix: ' *'} },
            { name: 'Email', index: 'Email', width: 200, align: 'left', formatter: 'mail', editable: true, edittype: 'text', editrules: { required: true, email: true }, formoptions: { elmsuffix: ' *'} },
            { name: 'PhoneNumber', index: 'PhoneNumber', width: 200, align: 'left', editable: true, edittype: 'text', editrules: { required: true, custom: true, custom_func: isValidPhone }, formoptions: { elmsuffix: ' *'} },
            { name: 'IsMarried', index: 'IsMarried', width: 200, align: 'left', editable: true, edittype: 'checkbox', editoptions: { value: "True:False" }, editrules: { required: true}}],
        pager: $('#listPager'),
        rowNum: 1000,
        rowList: [1000],
        sortname: 'ContactId',
        sortorder: "desc",
        viewrecords: true,
        imgpath: '/Content/Themes/Redmond/Images',
        caption: 'Contact List',
        autowidth: true,
        ondblClickRow: function (rowid, iRow, iCol, e) {
            $("#list").editGridRow(rowid, prmGridDialog);
        }
    }).navGrid('#listPager',
        {
            edit: true, add: true, del: true, search: false, refresh: true
        },
        updateDialog,
        updateDialog,
        updateDialog
    );
}); 

Contact Controller Update Action

The add/update/delete feature takes one URL where you can change the logic based on the operation type. The MVC Modal Binder will map the fields into your ViewModel in most cases. The exception is the “id” that is passed on the delete operation, but there is a way to get around that later in this post ;)

public ActionResult Update(ContactViewModel viewModel, FormCollection formCollection)
{
    var operation = formCollection["oper"];
    if (operation.Equals("add") || operation.Equals("edit"))
    {
        repository.SaveOrUpdate(new ContactViewModel
        {
            ContactId = viewModel.ContactId,
            DateOfBirth = viewModel.DateOfBirth,
            Email = viewModel.Email,
            IsMarried = viewModel.IsMarried,
            Name = viewModel.Name,
            PhoneNumber = viewModel.PhoneNumber
        });
    }
    else if (operation.Equals("del"))
    {
        repository.Delete(new ContactViewModel
        {
            ContactId = new Guid(formCollection["id"])
        });
    }

    return Content(repository.HasErrors.ToString().ToLower()); 
}

What About Using Complex Keys?

Instead of having ContactId (“key: true”) as your key to delete, you might have a more complex key to identify which item to delete. As it turns out, you can bind to the onclickSubmit event of the add/edit/delete dialog and change what data is POST’ed to the controller.

A nice side effect of this is that you name your property such that the MVC Modal Binder works.

Updated Dialog Object Literal

var updateDialog = {
    url: '<%= Url.Action("Update", "Contact") %>'
    , closeAfterAdd: true
    , closeAfterEdit: true
    , afterShowForm: function (formId) {
        $("#PhoneNumber").mask("(999) 999-9999");
        $("#DateOfBirth").datepicker();
    }
    , afterclickPgButtons: function (whichbutton, formid, rowid) {
        $("#PhoneNumber").mask("(999) 999-9999");
    }
    , modal: true
    , onclickSubmit: function (params) {
        var ajaxData = {};

        var list = $("#list");
        var selectedRow = list.getGridParam("selrow");
        rowData = list.getRowData(selectedRow);
        ajaxData = { ContactId: rowData.ContactId };

        return ajaxData;
    }
    , width: "400"
};

Updated Contact Controller Update Action

public ActionResult Update(ContactViewModel viewModel, FormCollection formCollection)
{
    var operation = formCollection["oper"];
    if (operation.Equals("add") || operation.Equals("edit"))
    {
        repository.SaveOrUpdate(new ContactViewModel
        {
            ContactId = viewModel.ContactId,
            DateOfBirth = viewModel.DateOfBirth,
            Email = viewModel.Email,
            IsMarried = viewModel.IsMarried,
            Name = viewModel.Name,
            PhoneNumber = viewModel.PhoneNumber
        });
    }
    else if (operation.Equals("del"))
    {
        repository.Delete(new ContactViewModel
        {
            ContactId = viewModel.ContactId
        });
    }

    return Content(repository.HasErrors.ToString().ToLower()); 
}

Conclusion

I hope you found the above article of some use in your everyday coding. The jqGrid also provides an inline editing feature similar to what you might experience in an Excel grid. You might look into that if you are interested.

Please give me your feedback. Thanks!

Download Source Code