我尝试使用jQuery的ajax()函数将一个对象数组传递给一个MVC控制器方法。当我进入PassThing() C#控制器方法时,参数"things“为空。我尝试过使用List类型作为参数,但也不起作用。我做错了什么?
<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; }
}
}
发布于 2015-03-27 00:28:41
你就不能这么做吗?
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用来标记你的动作
[HttpPost]
public void PassThings(IEnumerable<Thing> things)
{
// do stuff with things here...
}
发布于 2012-11-06 08:51:53
格式化您的数据可能是问题所在。尝试执行以下任一操作:
data: '{ "things":' + JSON.stringify(things) + '}',
或(来自How can I post an array of string to ASP.NET MVC Controller without a form?)
var postData = { things: things };
...
data = postData
发布于 2017-07-19 12:50:11
我能让它工作的唯一方法是将JSON作为字符串传递,然后使用JavaScriptSerializer.Deserialize<T>(string input)
对其进行反序列化,如果这是MVC4的默认反序列化器,那就很奇怪了。
我的模型有嵌套的对象列表,使用JSON数据我能得到的最好的结果是最上面的列表包含正确的项数,但是项中的所有字段都为空。
这种事情应该不会那么难。
$.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);
https://stackoverflow.com/questions/13242414
复制相似问题