Jun 4, 2011

Part 2: MVC 3 and DataTables with Inline Editor (Selection List)



THIS TUTORIAL HAD ACTUALLY BEING POSTED EARLIER THIS WEEK.  BUT DUE TO SENSITIVITY TO DATA AN PICTURE BEING USED I HAVE TO CHANGE AND USE ANOTHER CODE FOR THIS TUTORIAL.  I HOPE THIS VERSION IS BETTER THAN BEFORE. HAVE FUN!


Tonight I would like to share on how we could manipulate data using object into Json in MVC 3 easily.  On the same time, we will see how to create and customize JEditable to use Drop Down list with dynamic data we fetch from set of information that we stash in Models.

First of all, this tutorial require a bit knowledge on C#, ASP.NET and JS to clearly understand the example given in this tutorial.  Level of skill would be novice(or atleast if you have completed the tutorial given on the microsoft MVC, then you should understand this tutorial)

So let's begin...

To use JEditable with Datatables on MVC, please read this tutorial first before we implement the inline edit with dynamic selection.  That's the best tutorial available on the net discussing on how to use DataTables in MVC 3 with Razor view.  So I assume in this tutorial, all my readers already have a working DataTables with JEditables working in all columns and rows.


So I'll be working on with the source from Code Project tutorial on JEditable usage on MVC 3.  In this tutorial I'll emphasis on how to change inline edit text input into dynamic Dropdown list. First we have to make sure that we edit the Company.cs in Models folder to match like below.

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

namespace DataTableEditable.Models
{
    public class Company
    {
        static int nextID = 17;

        public Company()
        {
            ID = nextID++;
        }
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Town { get; set; }
    }

    public class Town
    {
        static int nextID = 5;
        public Town()
        {
            ID = nextID++;
        }
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

That's it for our Company and Town model.  The Town model will have town name and ID for our Dropdown list to list later.  While the Company model will contain all company information that we will display on our Datatables.

Before we proceed to play with the controller and the View, we need to create DataRepository first to make sure that there is a default data to used when we load the Ajax.  Otherwise, you will think that the tables fail to load because of no data in our DataRepository.  So copy the code below and put it inside our Models folder.

        public static IList getTown()
        {
            if (townData == null)
            {
                townData = new List();
                townData.Add(new Town() { Name = "Derbyshire" });
                townData.Add(new Town() { Name = "London" });
                townData.Add(new Town() { Name = "West Midlands" });
                townData.Add(new Town() { Name = "Isleworth" });
            }
            return townData;
        } 


Copy and paste this to your original DataRepository.cs that you have downloaded earlier.  The codes above will insert data each and everytime you first load the Ajax datatables.  So that's all for our Model in this tutorial.  Next, we will add some code to our controller in Ajax folder to be able to pass data from Town model to Ajax for our selection list.

This is what my controller will look like(add this code at the end of your CompanyController.cs):

        public JsonResult getTownList()
        {
            var town = DataRepository.getTown();
            var list = town.Select(c => new[]
                         { c.Name.ToString(), c.Name.ToString() });
            return Json(list);
        }

That modification made to send data from our list, to the Ajax once user click to edit the Town column.
Now, we have to prepare our Javascript to load on the page.  Code Project tutorial will write this section of javascript in Index.cshtml  but I prefer to use proper .js file.  So here is the script to enable select on Town column.

$(document).ready(function () {
        $('#myDataTable')
        .dataTable({ "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": 'AjaxDataProvider',
            "sPagination": "full_numbers",
            "aoColumns": [
                { "sName": "ID",
                    "bSearchable": false,
                    "bSortable": false,
                    "bVisible": false
                },
                { "sName": "COMPANY_NAME", sTitle: "My JEditable Table" },
          { "sName": "ADDRESS" },
          { "sName": "TOWN" }
      ]
        }).makeEditable({
            aoColumns: [
                    {},
                    {},
                    {
                        data: getTownList(),
                        type: "select",
                        submit: "OK"
                    }
                    ]
        });
    });
    function getTownList() {
        $.post('getTownList', {},
            function (data) {
                getTownList = validateJSON(data);
            },
            'json/javascript'
        );
        return getTownList;
    }

    function validateJSON(x) {
        var orig = x;
        var stgify = JSON.stringify(orig);
        var splitchar = ['\\"', '\',\'', '[', ']', '\"'];
        var joinchar = ['\'', '\':\'', '', '', ''];

        for (i = 0; i < 5; i++) {
            stgify = stgify.split(splitchar[i]);
            tmp = stgify.join(joinchar[i]);
            stgify = tmp;
        }
        stgify = "{" + stgify + "}";
        var finalEdit = stgify;
        return finalEdit;
    }

And thats all. Now we could play around with our table, edit the content inline, and use dropdown list to edit data with dynamic selection list data. Stay tune and bookmark my blog for the next tutorial on MVC 3.

Any comment and guide to simplify the codes will be appreciated. I know this code could be simplify in better way.


Thank you for your unbelievable support on Negative Zero - Permission to read and write blog for nearly 4 years. Don't forget to like Negative Zero on Facebook.
Blogirific.com Blog Directory





Post(s) you might like to read :

2 comments:

  1. In edit mode select control not binding please guide me

    ReplyDelete