【问题标题】:Passing Int Array to ASP .NET Controller将 Int 数组传递给 ASP .NET 控制器
【发布时间】:2021-02-04 20:27:48
【问题描述】:

我正在尝试将数组传递给控制器​​以更新那些匹配的记录 这是我传递数组的方式:

[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 但这似乎永远行不通,有没有更好的方法来归档我要归档的内容?

【问题讨论】:

  • 我不会做那样的网址。
  • 您需要一个自定义模型绑定器。 Google for ArrayModelBinder,很确定有博客文章
  • @DanielA.White 是的,那是为了测试目的

标签: c# asp.net asp.net-web-api


【解决方案1】:

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

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

模型.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
    }

然后您需要更改您的请愿书以发送发布请求,并且在请求正文中您需要发送类似的对象

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

查看 Ajax 文档以发送带有请求正文的发布请求,请记住,默认情况下,C# 控制器将 Content-Type 获取为 application/json,如果遇到问题,请在 Ajax 请求中考虑这一点。

【讨论】:

  • 我喜欢这个!试一试!
  • @cinafoy881 谢谢,你也可以试试第二种方案,你可以直接传数组,如你所见,那么两种方案都可以。
【解决方案2】:

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

     [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) {}
});

【讨论】:

    猜你喜欢
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多