[英]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.