簡體   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