Saturday, 18 April 2015

Returning a Customer List as JSON string via AJAX call using Newtonsoft.Json and populating a DropDown

Back to .Net Jason Serializer


public class CustomerList
    {
        public string CustomerAlias { get; set; }
        public string CustomerName { get; set; }
    }


Lets say we have a LIST<T> CustomerList (above) that we need to return as a JSON STRING via an AJAX call. Once we have the customer list on the client side, then we will populate a customer drop with it.


using Newtonsoft.Json;

[HttpPost]
        public JsonResult GetCustomers()
        {
            var customers = String.Empty;
            var isError = true;
            var message = String.Empty;
 
            try
            {
                //In a real world this list will be coming from DataBase
                var customersList = new List<CustomerList>
                {
                    new CustomerList {CustomerAlias = "CustomerOne", CustomerName = "Customer One"},
                    new CustomerList {CustomerAlias = "CustomerTwo", CustomerName = "Customer Two"},
                    new CustomerList {CustomerAlias = "CustomerThree", CustomerName = "Customer Three"}
 
                };
 
                if (customersList != null && customersList.Count > 0)
                {
                    //convert to JSON string
                    customers = JsonConvert.SerializeObject(customersList);
                    if (!String.IsNullOrWhiteSpace(customers))
                    {
                        isError = false;
                    }
                }
            }
            catch (Exception ex)
            {
                //Do error logging
            }
 
 
            if (isError)
            {
                message = "Unable to get customers list.";
            }
            var result = new JsonResult { Data = new { customer = customers, error = isError, message = message } };
            return JsonHelper.AddJsonUtf8Encoding(result);
        }

 JSON Helper class used by the above action

public class JsonHelper
    {
        public static JsonResult AddJsonUtf8Encoding(JsonResult result)
        {
            result.ContentEncoding = System.Text.Encoding.UTF8;
            result.ContentType = "application/json; charset=UTF-8";
            return result;
        }
    }

 AJAX Call - JQUERY

$.ajax({
    cache: false,
    url: "/Controller/Action", //URL to the action
    type: "POST",
    data: { random: Math.random() },
    error: function (xhr, ajaxOptions, thrownError) { //xhr, status, errorMsg
        //Display some error message here
    },
    success: function (result) {
        if (result.error) { 
            //Display some error message here -- result.message
        } else if (result.customer == "" || result.customer == null) {
            //Display some error message here -- result.message
        } else {
            //result.customer is a json string, we'll need to turn this into an object
            var customerList = JSON && JSON.parse(result.customer) || $.parseJSON(result.customer);
            if (!customerList || customerList.length <= 0) {
                //Display some error message here
            } else {
                //create dropdown object
                var customerDropDownList = document.getElementById("DropDownId");
                //clear current items from customer dropdown
                customerDropDownList.options.length = 0;
                //add new customers
                for (var i = 0; i < customerList.length; i++) {
                    var opt = document.createElement("option");
                    opt.text = customerList[i].CustomerName;
                    opt.value = customerList[i].CustomerAlias;
                    customerDropDownList.options.add(opt);
                }
            }
        }
    }
});