繁体   English   中英

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

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

通过超级代理向ASP.NET MVC3端点发出Ajax发布请求。 用户名正确绑定并以'foobar'出现。 但是,RoleIds(IEnumerable <int>)为null。

我当前的实现如下所示:

伺服器:(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]}

我所学到的东西我想我必须以以下格式发布请求:

UserName=foobar&RoleIds=1&RoleIds=2

如何使超级代理以正确的格式格式化请求,以便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))

暂无
暂无

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

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