【问题标题】:Passing an array to an MVC controller将数组传递给 MVC 控制器
【发布时间】:2018-03-31 16:05:15
【问题描述】:

我想将一组 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 现在的传递方式,有没有办法实现这一点?

【问题讨论】:

标签: c# asp.net-mvc asp.net-core controller asp.net-mvc-routing


【解决方案1】:

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);  

}

【讨论】:

  • 如果你要做一个 POST,那么它就是 data : JSON.stringify({ stringOfCustomerIds : arrCustomerIds }),contentType: 'application/json',方法是 public JsonResult GetCustomers(int[] stringOfCustomerIds)(让 ModelBinder 工作)
【解决方案2】:

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

[FromQuery(Name ="ids")]

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

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

这样制定属性

[FromQuery(Name = "kittens")] 那么你需要让你的查询看起来像

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

按照此方法,您将能够看到您的参数已正确填充。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2013-09-05
      • 2014-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-25
      相关资源
      最近更新 更多