How to create a multi-column Select2 control in ASP dot Net MVC LOB projects?

I use Select2 control for my ComboBoxes because of its simplicity and lightweight, but it comes with a hefty price, it has limited column variables to play around, the Id and the Text column variables.  And because of this, Select2 control is utterly useless on an LOB or an enterprise application.  But there is always a way around to the limitations.  The solution is to wrap the Text variable into a serialized JSON object, cool eh.  And here are the steps:

1. Of course, model first, create a POCO class model.  In the example code below, I have a Bank class, to which when I select a bank then I would like to get the GL Account associated with it.

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

namespace project.Models
{
    public class Bank
    {
        public Int64 Id { get; set; }
        public string Bank { get; set; }
        public Int64 AccountId { get; set; }
        public string Account { get; set; }
    }
}

2. Modify your Select2 controller.  Take note of the Text variable as highlighted in the code.  That variable is now equivalent to a JSON object using your Bank model.

public Models.SelectPagedObject Get(string searchTerm, int pageSize, int pageNum)
{
      var Items = from d in data.Banks
                  where d.Bank.Contains(searchTerm == null ? "" : searchTerm)
                  orderby d.Bank
                  select new Models.SelectObject
                  {
                       id = d.Id,
                       text = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(
                                  new Models.Bank
                                  {
                                      Id= d.Id,
                                      Bank = d.Bank,
                                      AccountId = d.AccountId,
                                      Account = d.Account.Account
                                  })
                  };

      Int64 Count = Items.Count();

      Models.SelectPagedObject PagedResult = new Models.SelectPagedObject();

      PagedResult.Total = Count;
      PagedResult.Results = Items.Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();

      return PagedResult;
}

3. Modify the Select2 AJAX call in the view.  Below is a typical ugly Javascript code that creates your Select2 control using the AJAX call.  As you can see I added two extended Select2 object methods, formatResult and formatSelection, these two methods will basically extract the Bank column of your Text JSON object so as to display that information upon listing and after selection respectively.

At the bottom of the code there is a change event that when fired it will parse the Text JSON so as to consume the other information, in our example it is the GL Account associated with the Bank information.

$('#Select2Bank').select2({
    placeholder: 'Bank',
    allowClear: false,
    ajax: {
        quietMillis: 150,
        url: '/api/SelectBank',
        dataType: 'json',
        cache: false,
        type: 'GET',
        data: function (term, page) {
            return {
                pageSize: $pageSize,
                pageNum: page,
                searchTerm: term
            };
        },
        results: function (data, page) {
            var more = (page * $pageSize) < data.Total;
            return { results: data.Results, more: more };
        }
    },
    formatResult: function (data) {
        var JSONObject = JSON.parse(data.text);
        return JSONObject["Bank"];
    },
    formatSelection: function (data) {
        if (data) {
            try {
                var JSONObject = JSON.parse(data.text);
                return JSONObject["Bank"];
            } catch (err) {
                return data.text;
            }
        } else {
            return "";
        }
    }
}).change(function () {
    var JSONObject = JSON.parse($('#Select2Bank').select2('data').text);

    $('#Select2Account').val(JSONObject["Account"]);
});

Below is the actual screen shot of the applied solution above.  So when the user change the Bank ComboBox the disabled Account Input field will be updated without communicating to the server.

b1

That’s it.  Happy coding and if you find this blog helpful, you can make the donation by clicking the Paypal button below.


					
Advertisements
About

Software developer living in the Philippines.

Posted in ASP.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Author

Harold Glenn P. Minerva
Software Developer / Tech Enthusiast
Living in the Philippines

View Harold Glenn Minerva's profile on LinkedIn

Instagram

Software Engineer - Seasonal and Range Trading Software. Magenta Trader is a powerful stock market visualization software that increases your probability of trading success.

Software Architect and Founder - Easyfis.com is a multi-tenant cloud-based Software-as-a-Service (SaaS) business app that caters to micro, small and medium trading businesses.

CTO and Co-Founder - We give your company the leverage by providing innovative software solutions products such as Point-of-Sales (POS), Financial Information System (FMIS), Payroll and DTR (HRIS), and many more.

%d bloggers like this: