简体   繁体   中英

Making ajax post to ASP.NET MVC endpoint with superagent, bind to IEnumerable<int> property

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM