传递Int数组给asp.net控制器



我试图将数组传递给控制器,以便更新那些匹配的记录下面是我传递数组的方法:

[Route("api/updateFile/{id}")]
[HttpGet]
[HttpPost]
public void updateFile(int[] ids, string FolderName, Int Key)
{
var FilesToUpdate = db.ActivityFiles.FirstOrDefault(x => x.id == ids); //ids containing 124,52,22,262,32
FilesToUpdate.id= FolderName;
FilesToUpdate.Key = Key;
_db.SaveChanges();
}

Ajax非常简单

$.ajax({url: '/api/updateFile/' + imgList  + '?FolderName=' + 545454 + '&Key=' + 777,
type: "GET",success: function (data) {console.log("image set updated - success! ");},
error: function (data) {}});

imgList包含:124,52,22,262,32但这似乎行不通,有没有更好的方法来存档我试图存档的东西?

如果你想通过api发送一个数组,那么你需要通过请求体发送它,然后你需要像这样更新你的代码

首先创建一个ModelBind类来存储数组

Model.cs


namespace Api.Models
{
public class Model
{
public int[] ids {get; set;}
}
}
[Route("api/updateFile")]
[HttpPost]
public void updateFile([FromBody] Model model, string FolderName, int Key)
{
// your code goes here in the ids parameter you have the array
}

然后您需要更改您的请愿以发送Post Request,并且在请求正文中您需要发送一个对象,如

{
"ids" : [124,52,22,262,32]
}

查看Ajax文档,发送带有请求体的post请求,请记住,默认情况下c#控制器将Content-Type作为application/json,然后如果您遇到问题,请在Ajax请求中考虑到这一点。

尝试使用这个控制器动作头:

[Route("api/updateFile/{folderName}/{key}")]
public void updateFile([FromBody]int[] ids, string folderName, int key)
{
var filesToUpdate = db.ActivityFiles.FirstOrDefault(x => ids.Contains(x.id) ); 
filesToUpdate.id= folderName;
filesToUpdate.Key = key;
_db.SaveChanges();
}

和这个Ajax:

$.ajax({
url: '/api/updateFile/545454/777',
data: [124,52,22,262,32],
success: function (result) {console.log("image set updated - success! ");},
error: function (err) {}
});

最新更新