Thursday, 21 July 2016

Post JSON to MVC controller

No comments
JQUERY

var array=[];
$("[name='Sync']").each(function () {               
                var key = ($(this).is(':checked'))
                if (key == false) {
                    var value = ($(this).attr('data-id'))
                    array.push({ key: key, value: value });
                }
            });            
            $.ajax({
                url: '@Url.Action("ChildChannelProductDB", "Products"),
                data: JSON.stringify(array),
                type: "POST",
                success: function (data, textStatus, XMLHttpRequest) {
                    SetData(data);
                }
            });



Model

  public class ArrayResponseModel
    {
        public string key { get; set; }
        public string value { get; set; }
    }

Controller

var resolveRequest = HttpContext.Request;
            List<ArrayResponseModel> model = new List<ArrayResponseModel>();
            resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
            string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
                 if (jsonString != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                model = (List<ArrayResponseModel>)serializer.Deserialize(jsonString, typeof(List<ArrayResponseModel>));
            }