将数组作为对象的一部分传递给Ajax调用

时间:2014-07-12 16:35:57

标签: javascript jquery ajax

到目前为止,我已经使用JSON.stringify成功地通过AJAX将一个字符串数组传递给我的控制器。

但是,现在我需要将该数组移动到另一个对象中,以便将更多数据传递给AJAX调用。

以下(以及许多其他尝试)导致jobRequest.Tests在传递给控制器​​时没有成员:

    function executeTests(testsToRun) {
        if (testsToRun.length > 0) {
            var jobRequest = new Object;
            jobRequest.SampleTitle = '@ViewBag.SampleTitle';
            jobRequest.SampleLanguage = '@ViewBag.SampleLanguage';
            jobRequest.Mode = '@ViewBag.SampleMode';
            jobRequest.Tests = JSON.stringify(testsToRun);
            $.ajax({
                url: '@Url.Action("ProcessJob", "ProcessJob")',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify({ 'jobRequest': jobRequest }),
                success: function (jobId) {
                    window.location.href = '@Url.Action("Index", "ProcessJob")' + '?id=' + jobId;
                }
            });
        }
    }

public class JobRequest
{
    public string SampleTitle { get; set; }
    public string SampleLanguage { get; set; }
    public string Mode { get; set; }
    public List<string> Tests = new List<string>();
}

public JsonResult ProcessJob(JobRequest jobRequest)
{
    ...

1 个答案:

答案 0 :(得分:2)

您可以像这样更改课程 JobRequest

public class JobRequest
{
    public string SampleTitle { get; set; }
    public string SampleLanguage { get; set; }
    public string Mode { get; set; }
    public List<string> Tests { get; set; }
}

并删除数组中的 JSON.stringify

jobRequest.Tests = testsToRun;