mvc ajax传递list,c# - MVC Send list through AJAX - Stack Overflow

First off I'm making the assumption that your $.ajax is for JQuery and not some other Javascript framework. Please correct me if that's wrong.

ASP.NET MVC can actually do what you are asking it to (resolve data sent via AJAX to a List, but it seems to have a difficult time doing it via a GET request. It would help to know which version of ASP.NET MVC you are using, as more is required to get this working on the older versions. However, what I'm suggesting should work on MVC 3 or 4.

When you send AJAX via JQuery using a GET request and passing it a JavaScript array, this is what you are sending to the server:

http://localhost:50195/FilterSessions/GetFilterSession?undefined=&undefined=

It's no wonder the model is null because no data is actually being sent.

I believe ASP.NET can accept objects (and even arrays of objects) like this, but it won't do so with it formatted as JSON (like via JSON.stringify) as that just results in the following request:

http://localhost:50195/FilterSessions/GetFilterSession?[{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22},{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22}]

The way you probably want to do this is with a POST request. ASP.NET MVC will actually accept a JSON string as POST data and will decode it and resolve the model properly. Your AJAX code works fine with a couple modifications:

$.ajax({

url: "/FilterSessions/GetFilterSession",

type: "POST", //Changed to POST

dataType: "json",

data: JSON.stringify(jsonFilters), //Pack data in a JSON package.

contentType: "application/json; charset=utf-8", //Added so ASP recognized JSON

traditional: true,

success: function (response) {

alert('Success!');

}

});

The controller you posted should recognize POST data already, but in case it doesn't, a simple [HttpPost] attribute is all you need:

[HttpPost]

public ActionResult GetFilterSession(List jsonFilters)

{

//Do things

return Json(false, JsonRequestBehavior.AllowGet);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值