Making Ajax post request to ASP.NET MVC3 endpoint by superagent. UserName bounds correctly and comes as 'foobar'. However, RoleIds (IEnumerable < int> ) comes as null.
My current implementation looks like this:
Server: (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) {
...
}
...
}
Client (Javascript):
const data = {
UserName: 'foobar',
RoleIds: [1, 2]
}
superagent.post('/AddUser')
.send(data)
.then((res) => console.log(res))
My request looks like this:
{"UserName":"foobar","RoleIds":[1,2]}
What I have learnt I guess I have to post my request in the following format:
UserName=foobar&RoleIds=1&RoleIds=2
How to make superagent to format the request in the correct format in order to MVC3 endpoint to bind it correctly? (In jQuery there was some traditional
option to deal with this.)
Ok got it working.
One should set Content-Type
as application/x-www-form-urlencoded
and then it sends the request in correct format like this:
UserName=foobar&RoleIds=1&RoleIds=2
So the request must be done like this:
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))