Json round trip on Web Api 2


send some data from the webapi (see webapi notes to get json formatted)

[HttpGet("GetProgramsbyMajMin/{dataIn}")]
        public List<KeyValuePair<string, string>> GetProgramsbyMajMin(string dataIn)
        {
 
            string[] dataArr = dataIn.Split('~');
 
            SRMajorMinor srMajorMinor = new SRMajorMinor();
            DataTable saTable = srMajorMinor.GetProgramsbyMajMin(dataArr[0], dataArr[1].Trim(), dataArr[2]);
            List<KeyValuePair<string, string>> majMin = new List<KeyValuePair<string, string>>();
            foreach (DataRow row in saTable.Rows)
            {
                majMin.Add(new KeyValuePair<string, string>(row.Field<string>("col_deg_maj_cd"), row.Field<string>("prg_name")));
            }
 
 
            return majMin;
        }
Then put it in an object in javascript

$.get("/GetProgramsbyMajMin/" + formattedData, function (data) {
 
            var JSONObject = eval(data);
 
        });
You can access it:

JSONObject.length for number of records
 
JSONObject[0] to see a row
 
JSONObject[0].Key <-- where key is a field name



To convert a simple datarow to json


on the server

 public static string GetJson(DataRow r)
        {
            int index = 0;
            StringBuilder json = new StringBuilder();
            foreach (DataColumn item in r.Table.Columns)
            {
                json.Append(String.Format("\"{0}\" : \"{1}\"", item.ColumnName, r[item.ColumnName].ToString()));
                if (index < r.Table.Columns.Count - 1)
                {
                    json.Append(", ");
                }
                index++;
            }
            return "{" + json.ToString() + "}";
        }
in the browser

 $.get("/api/jqueryapi/GetCompanyAddressInfo/" + $(compInput).val(), function (data) {
 
            var obj = $.parseJSON(data);
 
            if ($(compInput).attr("id") == "PNL_REC_COMP_NAME_id") {
                $("#PNL_REC_COMP_STREET_ADDRESS").val(obj.ADDRESS1);
                $("#PNL_REC_COMP_CITY").val(obj.ADDRESS2)
 
}
 
}


To pass highly complex tabular data to MCV using JSON objects


Key concepts here are:

Define a javascript object that is mirrored as a server side object.

Use jquery toJSON to serialize the js object to json

First define a complex javascript object

// this is a test object
function NetworkSearch() {
            var industries = new Array();
            industries[0] = $("#indId").val();
            var practices = new Array();
            //practices[0] = 12;
            var geographies = new Array();
            geographies[0] = $("#geoId").val();
            var domains = new Array();
            domains[0] = $("#domId").val();
            var keywords = $("#searchPhrase").val();
 
            return { industries: industries, practices: practices, geographies: geographies, domains: domains, keywords: keywords };
 
        }


Then define an equivalent object on the server (C#)

public class NetworkSearch
    {
        public int[] industries { get; set; }
        public int[] practices { get; set; }
        public int[] geographies { get; set; }
        public int[] domains { get; set; }
        public string keywords { get; set; }
 
    }
This is a simple javascript function to send the object to the server


function NetworkSearchTestJs() {
 
            document.body.style.cursor = "wait";
            var url = "/network/searchtest";
 
            var ns = new NetworkSearch();
 
 
            // key piece of functionality (jquery converts js object to json)
            var json = $.toJSON(ns);
 
            // this could probably be a simple jquery post
            JsAjax(url, json);
 
        }

Here is the JsAjax function. This is the only way that I could a json list to rehydrate on the server

// using raw xmlHttp as I could not get the jquery .post to rebuild the json into a c# object
            xmlHttp = new XMLHttpRequest();
            xmlHttp.open("POST","/ServiceRequestPost/PostAssetMatrix/", true);
            xmlHttp.setRequestHeader("Content-type", "application/json");
            xmlHttp.send($.toJSON(AssetsInfoList(srNumber)));
 
            // Create result handler
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    var return_data = xmlHttp.responseText;
                    if (return_data == "0") {
                        CloseDialog();
                        loadMyRequests()
                    }
 
 
                }
            }

A client side routine to build out an array of objects for the post
function AssetsInfoList() {
 
        var assetList = new Array();
 
        debugger;
 
        $('#userAssets tr').each(function () {
 
            assetInfo = new AssetInfo();
 
            assetInfo.ASSETTAG = $(this).find('td').eq(0).html().trim()
            assetInfo.DESCRIPTION = $(this).find('td').eq(1).html().trim()
            assetInfo.COMPANIES_NAME = $(this).find('td').eq(2).html().trim()
 
            assetList[assetList.length] = assetInfo;
 
        });
 
        return { assets: assetList };
    }

The complex C# object looks like this

public class AssetInfo {
        public string ASSETTAG  { get; set; }
        public string DESCRIPTION  { get; set; }
        public string COMPANIES_NAME  { get; set; }
        public string PLUSTMODEL  { get; set; }
        public string SERIALNUM { get; set; }
        public string QUANTITY  { get; set; }
        public string UNIT { get; set; }
        public string LOCATION { get; set; }
 
    }
 
    public class AssetsInfoList
    {
 
        public AssetInfo[] assets { get; set; }
    }
 




Then the object is rehydrated at the server

[HttpPost]
        public string PostAssetMatrix(AssetInfo[] assets)
        {
 
 
            return "0";
        }