如何通过ajax将字典<string,model>发送到ASP MVC中的控制器?

时间:2016-08-07 19:10:38

标签: jquery ajax asp.net-mvc

以下是测试操作:

[HttpPost]
public ActionResult testButton(MultiEventViewModel multiEventModel, Dictionary<String,Gift> giftList){
    return Json("success"); 
}

礼品型号

public class Gift {
    public string ASIN;
    public string title;
    public string imgSource;
    public string link;
    public int count;
}

提交按钮,字典及其填充方式:

_validation.isExists = function (obj) {
    return (((typeof obj) == 'undefined') || (obj === null)) ? false : true;
}
var giftList = {};
// Theres a list view with bunches of items from amazon, each item has an add button. 
// Each button's onclick will add that item's metadata to giftList. Here's how it being added. 
$(".addGift-primary").each(function () {
    $(this).click(function () {
        var grandParent = $(this).parent().parent();
        var title = grandParent.children(".hiddenTitle").html();
        var imgSource = grandParent.children("img").attr("src");
        var link = grandParent.find("a").attr("href");
        var ASIN = grandParent.attr("id");
        if (_validation.isExists(giftList[ASIN])) 
            giftList[ASIN].count += 1;
        else {
            giftList[ASIN] = {
                "ASIN": ASIN, "title": title,
                "imgSource": imgSource, "link": link, count: 1
            };
        }
        popupDialog("addGiftSuccessDialog")
    });
});

$("#addCustomGiftButton").click(function (e) {
    $.ajax({
        url: 'testButton',
        dataType: 'json',
        type: 'POST',
        data: { multiEventModel: $("#createEventForm").serializeObject(), giftList: giftList },
        success: function (e) {
            console.log("success ");
        }
    });
});

当我调试时,对于每个键值对,只传递键(我使用ASIN作为键),该值是具有所有null属性的Gift实例(这里是pic:{{3 }})

还有其他方法可以解决/解决这个问题吗?

项目(礼物)被动态添加到礼物列表中,因此除了词典之外,我不确定在控制器中还有什么用?

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,通过在发送之前将object / Dictionary转换为array / List:

动作:

[HttpPost]
public ActionResult testButton(MultiEventViewModel multiEventModel, List<Gift> giftList){
    return Json("success"); 
}

客户端:

var dictToList = function (obj) {
    var keys = Object.keys(obj);
    var result =[];
    for (var i = 0; i < keys.length; i++) result.push(obj[keys[i]]);
    return result
}
...
$("#addCustomGiftButton").click(function (e) {
    $.ajax({
        url: 'testButton',
        dataType: 'json',
        type: 'POST',
        data: { multiEventModel: $("#createEventForm").serializeObject(), giftList: dictToList(giftList) },
        success: function (e) {
            console.log("success ");
        }
    });
});

即使这并没有真正回答我的问题,但它确实完成了工作,我的实际问题也解决了。如果有人有任何其他解决方案,请告诉我。 (我还没有为更复杂的模型测试我的解决方案,所以它现在可能会起作用)