javascript - 将带有 int 列表的对象从 jquery 发布到 .net mvc 3 Controller

标签 javascript asp.net-mvc-3

我在通过 jQuery 将 JavaScript 对象发布到 .net MVC 3 Controller 时遇到困难。

我的目标:

var postData = {
    'thing1' : "whatever",
    'thing2' : "something else",
    'thing3' : [1, 2, 3, 4]
}

我的 jQuery 调用:

$.post('<%= Url.Action("Commit", "MassEdit") %>', postData, function (data) {
    // stuff
});

我的 View 模型:

public class SubmitThing {
    public string thing1 { get; set; }
    public string thing2 { get; set; }
    public IEnumerable<int> thing3 { get; set; }
}

我的 Controller :

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Commit(SubmitThing changes)
{
    return new EmptyResult();
}

问题是我的 Controller 中的“更改”对象的 thing1 等于“whatever”,thing2 等于“something else”,但 thing3 为空。现在我是否让 thing3 成为我的整数列表?

补充:我认为这更像是一个映射问题,而不是序列化问题。在我的 Controller 中,如果我查看

HttpContext.Request.Form["thing3[]"]

我得到一个值为“1,2,3,4”的字符串。但同样,我希望映射能够正常工作。

谢谢!

最佳答案

只需将其作为 json 发布即可:

    $.ajax({
        url: '<%= Url.Action("Commit", "MassEdit") %>',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({'thing1' : "whatever",
    'thing2' : "something else",
    'thing3' : [1, 2, 3, 4]
}),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {

        }
    });

它应该可以工作

关于javascript - 将带有 int 列表的对象从 jquery 发布到 .net mvc 3 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6361078/

相关文章:

javascript - HTML:动态 JavaScript 完全加载后

javascript - 使用javascript中的View处理 bool 值

asp.net-mvc-3 - 在 Razor/MVC3 中使用 @Html.ActionLink 获取原始文本?

asp.net-mvc-3 - 新鲜加载页面而不是从缓存中加载

asp.net-mvc - 返回 new EmptyResult() VS 返回 NULL

c# - 如何检测我的页面是否是回发的结果

javascript - 如何在没有 jQuery 的情况下将直接标记附加到 HEAD?

javascript - 单击选定文本后,窗口选择未提供更新范围

javascript - ajax成功后删除最近的li

javascript - 试图定位某人在 Vanilla JS 中点击的属性