How to send a list of data to Controller Action method using jQuery ajax method in ASP.NET MVC?

南笙酒味 提交于 2019-12-08 10:23:27

问题


Here is my Action Mehtod

public JsonResult GetById(IEnumerable<Guid> idList)
    {

        //.....
    }

And my JavaScript . I'm making an array of strings using li element's id property

var idArr = [];
        var list = $("#ulApplications li");
        $.each(list, function () {  idArr.push($(this).attr("id")) });          


        $.ajax(
            {
                type: "GET",
                url: "/rolemanagement/application/GetById/",
                contentType: false,
                datatype: "json",
                data: { 'idList': idArr },
                success:........

On my Action method I'm not getting any data.It seems I'm Missing something. thanks


回答1:


Change your ajax to

$.ajax({
  type: "GET",
  url: "/rolemanagement/application/GetById", // should use '@Url.Action(..)'
  dataType: 'json',
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify({ idList: idArr }), // stringify
  success: ....
})



回答2:


I tried out the below code which seems to be working fine,

$.ajax({
    type: "GET",
    url: "@Url.Action("GetById", new { area = "rolemanagement", controller = "application"})",
    data: { idList: [{ a: 'a' }, { a: 'b' }] },
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) { console.log(data); },
    error: function () { throw new Error("Error occurred."); }
});

which already given by @stephen where even stringify is not even required to send the data.




回答3:


After searching on stackoverflow and other blogs. I found a solution which is working for me, although above given answers are closely correct but they didn't worked for me. Here is my answer

var IdList = {idList:idArr}

        $.ajax(
            {
                type: "GET",
                url: "/rolemanagement/application/GetById/",
                contentType: false,
                datatype: "json",
                data: IdList,
                traditional: true,
                success:
                    function (data) {
                        alert(data);
                    },


来源:https://stackoverflow.com/questions/27422502/how-to-send-a-list-of-data-to-controller-action-method-using-jquery-ajax-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!