繁体   English   中英

将数组传递给MVC控制器

[英]Passing an array to an MVC controller

我想将ID数组传递给控制器​​。 最初,我是在查询字符串中添加每个ID,如下所示:

http:// localhost:4000 / customers / active?customerId = 1&customerId = 2&customerId = 3

然后在控制器端,我有一个方法可以接受这样的数组:

GetCustomers([FromQuery] int[] ids)
{
   ...
}

这很好用,但是在某些情况下,数组中有太多customerIds ,以致查询字符串变得太长,因此我不得不修改将查询传递给此方法的方式:

http:// localhost:4000 / customers / active?customerIds = 1,2,3

我通过将GetCustomers参数更改为接受字符串而不是int数组,然后在控制器中解析出customerIds (使用.Split(',') )来使解决方案起作用。

我觉得直接传递数组而不需要在服务器端修改字符串是比较干净的方法。 考虑到现在传递customerIds的方式,有没有办法实现这一目标?

1.使用帖子

2.使用AJAX和发送数据作为JSON

 $.ajax({
           type: "POST",
           url: "/Home/GetCustomers",
           data : { stringOfCustomerIds : JSON.stringify(arrCustomerIds)},
           dataType: "json",
           success: function (response) {
                 //do something with the response
           }

&在控制器端

public JsonResult GetCustomers(string stringOfCustomerIds )
{
     JObject CustomerIdsJson = JObject.Parse(listOfCustomerIds );

       foreach (JProperty property in CustomerIdsJson .Properties())
       {
           Console.WriteLine(property.ID+ " - " + property.Value);
       }

      return Json(output, JsonRequestBehavior.AllowGet);  

}

根据您对[FromQuery]属性的使用,可以看出您正在使用.NET Core(这仅适用于此)。 [FromQuery]无法知道要映射到参数的查询字符串的哪一部分,因此您必须提供一个Name参数,如下所示:

[FromQuery(Name ="ids")]

Name参数可以具有您想要的任何值。 只要您的查询与您选择的名称匹配即可。 因此,对于上面的示例:

?ids=2&ids=3&ids=4但是如果要像

[FromQuery(Name = "kittens")]那么您需要使查询看起来像

?kittens=2&kittens=3&kittens=4

按照这种方法,您将可以看到您的参数已正确填充。

您可以使用前端的POST请求和后端控制器的[FromBody]标签将ID作为JSON对象传递到消息的正文中。 这样,无论邮件正文中有多少个ID,您的URL都将看起来像这样: http://localhost:4000/customers/active 这也免除了您提取每个参数并将其推入新数组元素的麻烦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM