Send array via Ajax and bind to List<string> on MVC 4

怎甘沉沦 提交于 2019-12-13 00:41:17

问题


AJAX:

function systemsChanged(elem)
{
    var items = [];
    for (i = 0; i < elem.length; i++)
        if (elem[i].selected) {
            items.push(elem[i].value);
        }

    var post = { ids: items };

    $.ajax({
        type: "POST",
        traditional: true,
        url: "@Url.Action("LoadApplicationConfigs", "Application")",
        content: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(post),
        success: function (d) {
            alert(d.message);
        },
        error: function (xhr, textStatus, errorThrown) {
            alert("não rolo");
        }
    });
}

C# MVC 4:

[HttpPost]
public JsonResult LoadApplicationConfigs(IList<string> ids)
{
    object data = new
    {
        message = "aha!"
    };

    return new JsonResult() { Data = data };
}

It enters the post method but ids is set to null. I also tried changing ids to string[], not successfully. The return to ajax is fine: it shows the "aha!" alert. I just cant seem to be providing the accurate format to the mvc binder. Any thoughts?


回答1:


Update your ajax call to this:

$.ajax({
    type: "POST",
    traditional: true,
    url: "@Url.Action("LoadApplicationConfigs", "Application")",
    content: "application/json; charset=utf-8",
    dataType: "json",
    data: post,
    success: function(d) {
        alert(d.message);
    },
    error: function(xhr, textStatus, errorThrown) {
        alert("não rolo");
    }
});

This will work with or without the traditional option.



来源:https://stackoverflow.com/questions/25789727/send-array-via-ajax-and-bind-to-liststring-on-mvc-4

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