如何发送INT的列表,jQuery来ASP.net MVC默认模型绑定 [英] How to send a list of int with jQuery to ASP.net MVC Default Model Binder

查看:138
本文介绍了如何发送INT的列表,jQuery来ASP.net MVC默认模型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我送廉政局的名单使用jQuery这样的:

When I send a list of int's with jQuery like this:

$.ajax('@Url.Action("Execute")', {
    type: 'POST',
    data: {
        pkList: [1,2,3]
    }
});

然后jQuery将变换pkList对象,并通过邮寄这样发送:

Then jQuery will transform the pkList object and send it by post like this:

pkList[]:1
pkList[]:2
pkList[]:3

这将是罚款,如果服务器是PHP,但我使用Asp.NET MVC3,并尝试用默认的模型绑定来获取这些值:

Which would be fine if the server is PHP but I use Asp.NET MVC3 and try to get these values with the default model binder:

public ActionResult Execute(ICollection<int> pkList)

但pkList总是空,似乎默认模型绑定不能绑定。

But pkList is always null, it seems that the default model binder cannot bind it.

我如何正确地解决此问题?

How do I solve this correctly?

ADDED SOLUTION

我使用达林季米特洛夫的解决方案与设置传统的选项jQuery的:

I used the solution from Darin Dimitrov with setting the traditional option in jQuery:

$.ajax('@Url.Action("Execute")', {
    type: 'POST',
    traditional: true,
    data: {
        pkList: [1,2,3]
    }
});

现在的jQuery不会在 [] 添加到参数了,他们都是这样发送:

Now jQuery doesn't add the [] to the parameters anymore and they are sent like this:

pkList:1
pkList:2
pkList:3

和MVC的默认模型联得到正确的价值观。

And the MVC default model binder gets the values correctly.

希望这可以帮助别人。

推荐答案

您可以使用JSON请求,因为它可以让你给你希望的任何复杂的对象:

You could use a JSON request as it will allow you to send any complex objects you wish:

$.ajax({
    url: '@Url.Action("Execute")',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ pkList: [1, 2, 3] }), // you could throw any javascript object you like here
    success: function(result) {
        // process the results
    }
});

JSON.stringify 方法是建立在现代浏览器,如果你想支持旧版浏览器,你可以包括的 json2.js 脚本到您的网站。

The JSON.stringify method is built in modern browsers and if you want to support legacy browsers you could include the json2.js script to your site.

和回答你的问题,你可以使用设置传统:自从这个参数的真实选项来指示jQuery来退回到的传统的的序列化jQuery的1.4已经改变,如果你使用的是更高版本,你必须切换回参数序列化方式的可能性:

And to answer your question you could use set the traditional: true option to indicate to jQuery to fallback to traditional serialization of parameters since this has changed in jQuery 1.4 and if you are using a later version you have the possibility to switch back to the way parameters are serialized:

$.ajax({ 
    url: '@Url.Action("Execute")',
    type: 'POST',
    data: {
        pkList: [1, 2, 3]
    },
    traditional: true
});

这篇关于如何发送INT的列表,jQuery来ASP.net MVC默认模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆