Monday, January 7, 2013

Receiving and returning JSON data in C# and MVC

Suppose you have a C# class as follows:
    [Serializable]
    public class Spec
    {
        public string ID { get; set; }
        public int TypeID { get; set; }
        public string Value { get; set; }
        public int ForID { get; set; }
    }

To send an array of Specs from Javascript on the browser to an MVC controller you may issue:

         $.ajax({
            url: "/Create/UpdateSpecs",
            cache: false,
            data: { "SkuID": PID, "Specs": JSON.stringify(aspecs)
            },
            type: "POST"
        });

1) /Create/UpdateSpecs is your server-side endpoint.

2) JSON.stringify is from the JSON library. You may need to download jquery.json-2.2.js (or newer) if you you need to support older browsers.

3) To construct an array of Specs in Javascript you may issue something like the following code snippet where aspecs is your array of specs in Javascript and cnt is your array index:
aspecs[cnt] = { "ID": item.attr("id"), "TypeID": item.attr("typeid"), "Value": item.val(), "ForID": item.attr("for") };

On the C# MVC side, below, Specs has your JSON array that you could convert to a C# array by
calling JsonConvert.DeserializeObject and casting as array of Specs as follows:

 (Spec[])JsonConvert.DeserializeObject(Specs);

1) Important: You must have a reference to the library:
Newtonsoft.Json

2) The C# method returns a JsonResult. The return could be a complex data structure or a basic or intrinsic type.

        [HttpPost]
        public JsonResult UpdateSpecs(int SkuID, string Specs)
        {
            if (!string.IsNullOrEmpty(Specs))
            {
                Spec[] args = (Spec[])JsonConvert.DeserializeObject(Specs);

                ProductBinder UIBinder = new ProductBinder();


                return this.Json(UIBinder.UpdateSpecs(args, SkuID));
            }
            else
            {
                return null;
            }
        }