ASP MVC使用字符串数组作为参数向ActionResult发出Ajax请求

时间:2014-06-17 15:37:41

标签: jquery ajax arrays asp.net-mvc asp.net-mvc-4

我有一个小的网络应用程序,必须今晚完成,我坚持这个问题。我正在从Index视图到我的HomeController做一个ajax请求,它传递一些参数,包括一个字符串数组。

我在控制台中的字符串数组的输出是:[“text1”,“text2”]但在actionresult中我得到这个字符串[0] =“text1,text1”而不是字符串[0] =“text1 “和字符串[1] =”text2“。

以下是我的代码!

jQuery填充字符串数组(包装在onload中):

 var keywords = [];

 $("#menu-jesus a").on("click", function () {
        var keyword = $(this).text();
        keywords.push(keyword);

        getFilteredStatues();
        showDescription(keyword);

        $('#statue-info').hide();
    });

的Ajax:

$.ajax({
            type: "GET",
            cache: false,
            url: '@Url.Action("GetFilteredStatues")?height=' + queryString[0]
            + "&material=" + queryString[1]
            + "&keywords=" + keywords
            + "&itemsPerPage=" + itemsPerPage,
            dataType: "html",
            success: function (data) {
                $("#pictures").html(data);
                showSearchTerms();
                hideSearchTermDiv();
                getStatueInfo();

                if (itemsPerPage >= 304) {
                    $(".more-results").hide();
                }
            },
        });

的ActionResult:

    public ActionResult GetFilteredStatues(string height, string material, string[] keywords, int itemsPerPage)
    {
        var h = height != "undefined" ? height : "";
        var m = material != "undefined" ? material : "";

        var statues = db.GetFilteredStatues(h, m, keywords, itemsPerPage);

        return PartialView("PicturesResult", new IndexModel(statues));
    }

我感谢任何提示! THX。

2 个答案:

答案 0 :(得分:1)

要为模型绑定器选择关键字数组,您需要使用以下URL:

keywords=string1&keywords=string2

如果您知道关键字中只有两个元素,那么您可以

+ "&keywords=" + keywords[0]
+ "&keywords=" + keywords[1]

如果关键字中有任意数量的元素,那么您需要遍历数组并每次添加一个字符串+ =“& keywords =”+ keywords [i]

答案 1 :(得分:1)

将您的请求更改为

    var data = {
        height: queryString[0],
        material: queryString[1],
        keywords: JSON.stringify(keywords),
        itemsPerPage: itemsPerPage,
    };

$.ajax({
            type: "GET",
            cache: false,
            url: '@Url.Action("GetFilteredStatues")'
            dataType: "html",
            contentType = 'application/json',
            data: JSON.stringify(data)
            success: function (result) {
                $("#pictures").html(result);
                showSearchTerms();
                hideSearchTermDiv();
                getStatueInfo();

                if (itemsPerPage >= 304) {
                    $(".more-results").hide();
                }
            },
        })