使用AJAX后的JavaScript数组到ASP.NET MVC控制器 [英] Post JavaScript array with AJAX to asp.net MVC controller

查看:101
本文介绍了使用AJAX后的JavaScript数组到ASP.NET MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器:

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

我要发布的参数通过AJAX控制器。路过 INT projectId 是没有问题的,但我不能设法发布 INT []

I'd like to post the parameters to the controller via AJAX. Passing the int projectId isn't a problem, but I can't manage to post the int[].

我的JavaScript code:

My JavaScript code:

function sendForm(projectId, target) {
    $.ajax({
        traditional: true,
        url: target,
        type: "POST",
        data: { projectId: projectId, useraccountIds: new Array(1, 2, 3) },
        success: ajaxOnSuccess,
        error: function (jqXHR, exception) {
            alert('Error message.');
        }
    });
}

我试过跟一个测试数组,但没有成功。 :( 我也试着设置传统:真正的的contentType:应用/ JSON的;字符集= UTF-8,但没有成功,以及...

I tried it with a test array but no success. :( I also tried to set traditional: true, or contentType: 'application/json; charset=utf-8' but no success as well ...

INT [] useraccountIds 贴到我的控制器始终为空。

The int[] useraccountIds posted to my controller is always null.

推荐答案

您可以定义一个视图模型:

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)
{
    ...
}

和最后调用它:

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.');
        }
    });
}

这篇关于使用AJAX后的JavaScript数组到ASP.NET MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆