简体   繁体   English

使用超级代理将Ajax发布到ASP.NET MVC端点,并绑定到IEnumerable <int> 属性

[英]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. 通过超级代理向ASP.NET MVC3端点发出Ajax发布请求。 UserName bounds correctly and comes as 'foobar'. 用户名正确绑定并以'foobar'出现。 However, RoleIds (IEnumerable < int> ) comes as null. 但是,RoleIds(IEnumerable <int>)为null。

My current implementation looks like this: 我当前的实现如下所示:

Server: (C#, MVC3) 伺服器:(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): 客户端(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? 如何使超级代理以正确的格式格式化请求,以便MVC3端点正确绑定它? (In jQuery there was some traditional option to deal with this.) (在jQuery中,有一些traditional选项可以解决这个问题。)

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: 应该将Content-Type设置为application/x-www-form-urlencoded ,然后以正确的格式发送请求,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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