Saturday 7 January 2017

Post List of string from ajax to controller

Here is the proper way of posting a list of string from ajax to controller.

Ajax setup one way:
           var stringArray = new Array();
            stringArray[0] = "item1";
            stringArray[1] = "item2";
            stringArray[2] = "item3";
         
            $.ajax({
                type: "POST",
                url: '@Url.Action("Search", "Home")',
                data: JSON.stringify({ listkey: stringArray }),
            success: function (data) {
                alert(data.Result);
            },
            dataType: "json",           
            contentType: 'application/json; charset=utf-8',
             });

Ajax Setup second way:

 $.ajax({
                type: "POST",
                url: '@Url.Action("Search", "Home")',
                data: { listkey: stringArray },
            success: function (data) {
                alert(data.Result);
            },
            dataType: "json",
            traditional: true
             });

Now,Controller:
 public ActionResult Search(List<string> listkey)
        {
            var n = listkey;
            return Json(new { });
        }

Thanks,