2017-10-19 184 views
0

我想將一個ID數組傳遞給控制器​​。本來我是將每個ID查詢字符串,像這樣:將數組傳遞給MVC控制器

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 PARAMS接受字符串而不是一個int陣列工作,然後(使用.Split(',')

感覺好像它是清潔器傳遞一個陣列解析的customerIds出在控制器直接而不是必須修改服務器端的字符串。有沒有辦法通過customerIds現在通過的方式來實現?

+0

https://stackoverflow.com /問題/ 37768245/web的API傳遞陣列-的-整數字句法/ 37768858#3776 8858 – Nkosi

+0

[模型綁定逗號分隔的查詢字符串參數](https://stackoverflow.com/q/9584573/3110834) –

+0

動作是POST還是GET? – Nkosi

回答

0

您可以使用前端的POST請求和後端控制器上的[FromBody]標籤,將消息正文中的ID作爲JSON對象傳遞。這樣,您的網址將如下所示:http://localhost:4000/customers/active無論郵件正文中有多少個ID。它還爲您節省了將每個參數提取並推送到新數組元素的麻煩。

1

1. USE POST

2.使用AJAX &發送數據AS 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); 

} 
+0

如果你打算做一個POST,那麼它將只是'data:JSON.stringify({stringOfCustomerIds:arrCustomerIds}),'contentType:'application/json'',並且方法將會是'public JsonResult GetCustomers(int [] stringOfCustomerIds)'(讓'ModelBinder'完成它的工作) –

相關問題