将数组传递给MVC控制器
我想将一个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
现在通过的方式来实现?
您可以使用前端的POST请求和后端控制器上的[FromBody]
标签,将消息正文中的ID作为JSON对象传递。这样,您的网址将如下所示:http://localhost:4000/customers/active
无论邮件正文中有多少个ID。它还为您节省了将每个参数提取并推送到新数组元素的麻烦。
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);
}
如果你打算做一个POST,那么它将只是'data:JSON.stringify({stringOfCustomerIds:arrCustomerIds}),'contentType:'application/json'',并且方法将会是'public JsonResult GetCustomers(int [] stringOfCustomerIds)'(让'ModelBinder'完成它的工作) –
https://stackoverflow.com /问题/ 37768245/web的API传递阵列-的-整数字句法/ 37768858#3776 8858 – Nkosi
[模型绑定逗号分隔的查询字符串参数](https://stackoverflow.com/q/9584573/3110834) –
动作是POST还是GET? – Nkosi