使用超级代理将 ajax post 转换为 ASP.NET MVC 端点,绑定到 IEnumerable<int> 属性
Making ajax post to ASP.NET MVC endpoint with superagent, bind to IEnumerable<int> property
通过超级代理向 ASP.NET MVC3 端点发出 Ajax post 请求。 UserName 正确绑定并显示为 'foobar'。
但是,RoleIds (IEnumerable < int> ) 为空。
我当前的实现如下所示:
服务器:(C#、MVC3)
public class AddUserViewModel
{
public string UserName { get; set;}
public IEnumerable<int> RoleIds { get; set; }
}
public class UserManagementController : Controller {
...
[HttpPost]
public virtual ActionResult AddUser(AddUserViewModel addUserViewModel) {
...
}
...
}
客户(Javascript):
const data = {
UserName: 'foobar',
RoleIds: [1, 2]
}
superagent.post('/AddUser')
.send(data)
.then((res) => console.log(res))
我的请求是这样的:
{"UserName":"foobar","RoleIds":[1,2]}
我学到了什么 我想我必须 post 我的请求格式如下:
UserName=foobar&RoleIds=1&RoleIds=2
如何让 superagent 以正确的格式格式化请求,以便 MVC3 端点正确绑定它? (在 jQuery 中有一些 traditional
选项可以处理这个问题。)
好的,成功了。
应该将 Content-Type
设置为 application/x-www-form-urlencoded
然后它以正确的格式发送请求,如下所示:
UserName=foobar&RoleIds=1&RoleIds=2
所以请求必须这样:
const data = {
UserName: 'foobar',
RoleIds: [1, 2]
}
superagent.post('/AddUser')
.send(data)
.set('Content-Type', 'application/x-www-form-urlencoded')
.then((res) => console.log(res))
通过超级代理向 ASP.NET MVC3 端点发出 Ajax post 请求。 UserName 正确绑定并显示为 'foobar'。 但是,RoleIds (IEnumerable < int> ) 为空。
我当前的实现如下所示:
服务器:(C#、MVC3)
public class AddUserViewModel
{
public string UserName { get; set;}
public IEnumerable<int> RoleIds { get; set; }
}
public class UserManagementController : Controller {
...
[HttpPost]
public virtual ActionResult AddUser(AddUserViewModel addUserViewModel) {
...
}
...
}
客户(Javascript):
const data = {
UserName: 'foobar',
RoleIds: [1, 2]
}
superagent.post('/AddUser')
.send(data)
.then((res) => console.log(res))
我的请求是这样的:
{"UserName":"foobar","RoleIds":[1,2]}
我学到了什么 我想我必须 post 我的请求格式如下:
UserName=foobar&RoleIds=1&RoleIds=2
如何让 superagent 以正确的格式格式化请求,以便 MVC3 端点正确绑定它? (在 jQuery 中有一些 traditional
选项可以处理这个问题。)
好的,成功了。
应该将 Content-Type
设置为 application/x-www-form-urlencoded
然后它以正确的格式发送请求,如下所示:
UserName=foobar&RoleIds=1&RoleIds=2
所以请求必须这样:
const data = {
UserName: 'foobar',
RoleIds: [1, 2]
}
superagent.post('/AddUser')
.send(data)
.set('Content-Type', 'application/x-www-form-urlencoded')
.then((res) => console.log(res))