通过ajax将复杂对象发送到控制器

时间:2017-03-02 09:40:22

标签: javascript c# jquery ajax asp.net-mvc

我正试图通过ajax传递一些复杂的数据来调用我的控制器。

我的控制器的动作方法。

public ActionResult CalculatePremium(QuoteDetailsViewModel quoteDetails)
{
    ViewBag.Message = "Your application description page.";

    return View();
}

Javascript代码:

quoteDetails = {
    StartDate: '10-10-2016',
    Drivers: [{ Name: 'Test', Occupation: 'Test2', 
       DateOfBirth: '10-10-1985'}, { Name: 'Test2', Occupation: 'Test4',
       DateOfBirth: '10-10-1945' }],
    Claims: ['5-5-2010']
    };


    $.ajax({
        type: "GET",
        url: '/Home/CalculatePremium',
        contentType: "application/json; charset=utf-8",
        data: quoteDetails,
        dataType: "json",
        success: function () { alert('Success'); },
        error: function (xhr, status, error) { alert('Error:'); }
    });

查看模型(不要担心字符串被用于DateTime - 它只是用于测试)

public class QuoteDetailsViewModel
{
    public string StartDate { get; set; }
    public List<Driver> Drivers { get; set; }
    public List<string> Claims { get; set; }
}

public class Driver
{
    public string Name { get; set; }
    public string Occupation { get; set; }
    public string DateOfBirth { get; set; }
}

当我调用action方法时,对象将填充以下内容:

{MotorInsuranceCalculator.Models.QuoteDetailsViewModel}
Claims: null
Drivers: Count = 2
StartDate: "10-10-2016"

quoteDetails.Drivers
Count = 2
[0]: {MotorInsuranceCalculator.Models.Driver}
[1]: {MotorInsuranceCalculator.Models.Driver}

quoteDetails.Drivers[0]
{MotorInsuranceCalculator.Models.Driver}
DateOfBirth: null
Name: null
Occupation: null

quoteDetails.Drivers[1]
{MotorInsuranceCalculator.Models.Driver}
DateOfBirth: null
Name: null
Occupation: null

非常感谢任何解决此问题的帮助。

2 个答案:

答案 0 :(得分:7)

contentType是您要发送的数据类型,因此application/json;默认为application / x-www-form-urlencoded;字符集= UTF-8。

如果您使用application/json,则必须使用JSON.stringify()才能发送JSON个对象。

JSON.stringify()将javascript对象转换为json文本并将其存储在字符串中。

$.ajax({
    type: "POST",
    url: '/Home/CalculatePremium',
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(quoteDetails),
    dataType: "json",
    success: function () { alert('Success'); },
    error: function (xhr, status, error) { alert('Error:'); }
});

此外,您必须使用HttpPost动词才能执行post请求。

[HttpPost]
public ActionResult CalculatePremium(QuoteDetailsViewModel quoteDetails)
{
   ViewBag.Message = "Your application description page.";
   return View();
}

答案 1 :(得分:2)

我想你必须做JSON.stringify(quoteDetails)才能将它作为json对象发送。

还要确保在服务器端收到json时解析json。