【发布时间】:2014-08-28 01:38:58
【问题描述】:
我在使用 $.post() 和我的 mvc 控制器时遇到了一些问题。
我在网上尝试了几个例子,堆栈溢出是这样的:How can I post an array of string to ASP.NET MVC Controller without a form?
但没有成功。我只是想将一个字符串数组传递给我的控制器:
[HttpPost]
public HttpResponseMessage Post([FromBody]List<string> idList, string request, bool auto)
{
LogHelper.Log(Severity.Info, "Just entered in POST api/files");
var fileList = new List<string>();
switch (request)
{
case "Activate":
fileList = auto ? _bendingsServies.GetBendigsToCome() : idList;
_filesServices.Activate(fileList);
break;
case "Archive":
fileList = auto ? _filesServices.GetFilesToArchive() : idList;
_filesServices.Archive(fileList);
break;
default:
return ControllerContext.Request.CreateResponse(HttpStatusCode.BadRequest);
break;
}
return ControllerContext.Request.CreateResponse(HttpStatusCode.OK);
}
和我的jQuery:
@using System.Configuration
var api_url = "@ConfigurationManager.AppSettings["apiUrl"]";
$(document).ready(function() {
// ---- Ajax calls ---- //
$("#archivebutton").click(function() {
var url = api_url + "Files?request=Archive&auto=false";
var fileList = ["10", "14", "12"];
var postData = { idList: fileList }
$.post(url, $.param(postData,true));
});
});
在我尝试过的所有内容中,idList 在我尝试时总是包含 0 个元素。
// ---- 编辑 ---- //
如果我将数据封装在 json 对象中,我可以发送数据:
$("#activatebutton").click(function() {
var url = api_url + "Files?request=Activate&auto=false";
var fileList = ["this", "is", "a", "test"];
$.post(url, { fileList: fileList});
});
这是请求:
【问题讨论】:
-
如果你直接传递fileList而不将它包装在postData中会发生什么? $.post(url, $.param(fileList, true));
-
尝试不为“shallow”集合指定
traditional。只需$.param(postData)。 -
不……在另一边仍然什么都没有。
标签: jquery ajax asp.net-mvc api rest