Post JavaScript array with AJAX to asp.net MVC controller

前端 未结 6 2184
长情又很酷
长情又很酷 2020-12-01 12:23

My controller:

[HttpPost]
public ActionResult AddUsers(int projectId, int[] useraccountIds)
{
    ...
}

I\'d like to post the parameters to

6条回答
  •  独厮守ぢ
    2020-12-01 13:04

    You could define a view model:

    public class AddUserViewModel
    {
        public int ProjectId { get; set; }
        public int[] userAccountIds { get; set; }
    }
    

    then adapt your controller action to take this view model as parameter:

    [HttpPost]
    public ActionResult AddUsers(AddUserViewModel model)
    {
        ...
    }
    

    and finally invoke it:

    function sendForm(projectId, target) {
        $.ajax({
            url: target,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ 
                projectId: projectId, 
                userAccountIds: [1, 2, 3] 
            }),
            success: ajaxOnSuccess,
            error: function (jqXHR, exception) {
                alert('Error message.');
            }
        });
    }
    

提交回复
热议问题