如何将$(" form")。serialize()与AJAX方法中的数组列表传递给mvc控制器?

时间:2015-02-05 07:01:37

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

我必须将模型以及另一个数组列表值从javascript传递给控制器​​。

Javascript代码

$("#SaveData").click(function (e) {

    debugger

    var formdata = $("form").serialize();

    var list = new Array();
    var postData;
    $('input.chkevent').each(function () {
        debugger

        if (this.checked == true) {

            var parent_id = this.parentElement;
            var par2 = parent_id.previousElementSibling;
            var par3 = par2.previousElementSibling;
            var child = par3.childNodes[0];
            var child_val = child.defaultValue;

            var arr_date = this.parentElement.nextElementSibling.childNodes[0].value;
            var dep_date = this.parentElement.nextElementSibling.nextElementSibling.childNodes[0].value;
            var id = new Array(); ;
            id.push(child_val, arr_date, dep_date);
            list.push(id);
            postData = {values: list };

        }

    });

    $.ajax({
        type: "POST",
        url: "/umbraco/Surface/HomeSurface/FormData",

        data: (formdata ? formdata + "&" : "") + "values=" + postData,
        traditional: true,


        success: function (data) {
            //alert("ajax request to server succeed");
        }

    });

});

我只获得了一种数据,postDataformdata,但我需要两种数据传递控制器方法,如下所示:

public ActionResult FormData(PERSON_MASTER person, string[] values)
    {}

PERSON_MASTER.cs

public class PERSON_MASTER
{
    [Key]
    public int PERSON_ID { get; set; }

    public string ICARD_ID { get; set; }

   [Required]
    public string FNAME { get; set; }

  [Required]
    public string LNAME { get; set; }

    public string GENDER { get; set; }


    [DataType(DataType.Date)]
    public DateTime DOB { get; set; }

   [Required]
    public int? CITY_ID { get; set; }

    public int? STATE_ID { get; set; }

   [Required]
    public int? COUNTRY_ID { get; set; }

    public string CONTACT_NO { get; set; }

}

提前致谢。

2 个答案:

答案 0 :(得分:0)

试试这个,未经测试:

var model = {
    person: $("form").serialize(),
    values: list 
};

$.ajax({
        type: "POST",
        url: "/umbraco/Surface/HomeSurface/FormData",

        data: JSON.stringify(model),
        traditional: true,

        success: function (data) {
        //alert("ajax request to server succeed");
        }
});

答案 1 :(得分:0)

每当我将数据传递给控制器​​时,我都要确保参数名称与控制器中的参数名称相对应:

$.ajax({
        type: "POST",
        url: "/umbraco/Surface/HomeSurface/FormData",

        data: {
            person: formdata,
            values: list
        },
        traditional: true
    });

更新:您还必须确保参数具有相同的形状。在您的代码中,您将多维数组传递给非多维数组