首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用jQuery Ajax将对象列表传递给MVC控制器方法

使用jQuery Ajax将对象列表传递给MVC控制器方法
EN

Stack Overflow用户
提问于 2012-11-06 08:01:08
回答 10查看 328.3K关注 0票数 123

我尝试使用jQuery的ajax()函数将一个对象数组传递给一个MVC控制器方法。当我进入PassThing() C#控制器方法时,参数"things“为空。我尝试过使用List类型作为参数,但也不起作用。我做错了什么?

代码语言:javascript
复制
<script type="text/javascript">
    $(document).ready(function () {
        var things = [
            { id: 1, color: 'yellow' },
            { id: 2, color: 'blue' },
            { id: 3, color: 'red' }
        ];

        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: '/Xhr/ThingController/PassThing',
            data: JSON.stringify(things)
        });
    });
</script>

public class ThingController : Controller
{
    public void PassThing(Thing[] things)
    {
        // do stuff with things here...
    }

    public class Thing
    {
        public int id { get; set; }
        public string color { get; set; }
    }
}
EN

回答 10

Stack Overflow用户

发布于 2015-03-27 00:28:41

你就不能这么做吗?

代码语言:javascript
复制
var things = [
    { id: 1, color: 'yellow' },
    { id: 2, color: 'blue' },
    { id: 3, color: 'red' }
];
$.post('@Url.Action("PassThings")', { things: things },
   function () {
        $('#result').html('"PassThings()" successfully called.');
   });

...and用来标记你的动作

代码语言:javascript
复制
[HttpPost]
public void PassThings(IEnumerable<Thing> things)
{
    // do stuff with things here...
}
票数 38
EN

Stack Overflow用户

发布于 2012-11-06 08:51:53

格式化您的数据可能是问题所在。尝试执行以下任一操作:

代码语言:javascript
复制
data: '{ "things":' + JSON.stringify(things) + '}',

或(来自How can I post an array of string to ASP.NET MVC Controller without a form?)

代码语言:javascript
复制
var postData = { things: things };
...
data = postData
票数 14
EN

Stack Overflow用户

发布于 2017-07-19 12:50:11

我能让它工作的唯一方法是将JSON作为字符串传递,然后使用JavaScriptSerializer.Deserialize<T>(string input)对其进行反序列化,如果这是MVC4的默认反序列化器,那就很奇怪了。

我的模型有嵌套的对象列表,使用JSON数据我能得到的最好的结果是最上面的列表包含正确的项数,但是项中的所有字段都为空。

这种事情应该不会那么难。

代码语言:javascript
复制
    $.ajax({
        type: 'POST',
        url: '/Agri/Map/SaveSelfValuation',
        data: { json: JSON.stringify(model) },
        dataType: 'text',
        success: function (data) {

    [HttpPost]
    public JsonResult DoSomething(string json)
    {
        var model = new JavaScriptSerializer().Deserialize<Valuation>(json);
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13242414

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档