C# 将字符串数组传递给操作
我无法通过HTTP get将字符串数组传递给我的操作。我的HTTP GET执行以下操作: 我的代码如下所示C# 将字符串数组传递给操作,c#,asp.net-mvc,C#,Asp.net Mvc,我无法通过HTTP get将字符串数组传递给我的操作。我的HTTP GET执行以下操作: 我的代码如下所示 [HttpGet] public ActionResult Add(params string[] id) { // I expect this: // id = string[]{"1","2","3","4"} // I get this: // id always comes in as {string[1]}... aka.
[HttpGet]
public ActionResult Add(params string[] id)
{
// I expect this:
// id = string[]{"1","2","3","4"}
// I get this:
// id always comes in as {string[1]}... aka. string array with one element
// id[0] is "" - aka. the first element is always an empty string
}
我的HTTP Get可能采用的方式有:
http://www.example.com/Add?id=1
http://www.example.com/Add?id=1&id=2&id=3&id=4
http://www.example.com/Add/1
- 重载方法(不能重载控制器方法)
- 以逗号分隔的字符串形式传入ID,虽然有效,但很粗糙
$.ajax({
url: '/Controller/Method?id=2&id=3',
type: 'GET',
datatype: "json",
processData: false,
contentType: "application/json; charset=utf-8",
async: true,
success: function(response){},
error: function(response){}
});
C#控制器:
[HttpGet]
public ActionResult ExportRecords(string[] id)
{
foreach(string value in id)
{
System.Diagnostics.Debug.Writeline(value);
}
return View();
}
删除
参数
keyword@StephenMuecke我试过了。如果GET以http://www.example.com/Add/1
假设您使用的是默认路由,则需要另一种方法(该方法要求参数为int-id
(或string-id
)-而不是数组)@StephenMuecke抱歉,我不完全清楚我的身份证,他们也会有字母。我用数字把问题简化了一点:它的int
或string
是否真的不重要:)可能有一种方法可以通过自定义路由和方法中的两个参数(例如(string[]id,string xx)来实现这一点
其中前两个url将绑定到id
,第三个url将绑定到xx
——但是您需要在方法中进行条件检查。这与OP的问题无关,当然也不能解决url为../Add/1
和contentType:“application/json;charset=utf-8”的情况,
对于GET来说毫无意义,并且您的代码会抛出一个异常,因为数据类型:“json”,
(该方法返回html)这并没有解决OP的第三种情况(其中值是路由值,而不是查询字符串值-请求。QueryString
将是一个空集合),谁会继续投票?它没有回答问题!