将字符串数组从ajax传递给c#web方法

时间:2013-12-19 13:13:44

标签: c# javascript ajax jquery

嗨,我有以下代码

我怎么能最好传递一个数组,它将包含一个ID号和一个动态生成的文本框中的值,然后传递给后端到C#

var listoftextboxesWithValues = new Array();
var listoftextboxesWithID = new Array();
var i = 0;
$.each(listOftxtPriceTypeID, function (index, value) {
    listoftextboxesWithID[i] = value.ID.toString();
    listoftextboxesWithValues[i] = $("#txtPriceTypeID" + value.ID).val().toString();
    i++;
});

//---Till here the data in the above arrays is as expected, the problem starts below in the data :

$.ajax({
    type: "POST",
    url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
    data: "{subCategoryID : '" + parseInt(subcategoryID) + "',name: '" + name + "',description: '" + description + "',quantity: '" + parseInt(quantity) + "',supplier: '" + supplier + "',vatRate: '" + parseFloat(VatRate) + "',colorID: '" + parseInt(colorID) + "',brandID: '" + parseInt(brandID) + "',imagePath: '" + fileNameGUID + "',listOfTextBoxes: '" + JSON.stringify(listoftextboxesWithValues) + "',listOfTextBoxesValues: '" + JSON.stringify(listoftextboxesWithID) + "' }",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        alert("oh yeh");
    },
    error: function (error) {
        alert("An Error Occured");
    }
}); 



[WebMethod]
    public static void StoreNewProduct(int subCategoryID, string name, string description, int quantity, 
        string supplier, float vatRate, int colorID, int brandID, string imagePath, string[]  listOfTextBoxesID, string[]  listOfTextBoxesValues )
    {
        Product p = new Product();
        ProductPriceType ppt = new ProductPriceType();

        p.CategoryID = subCategoryID;
        p.Name = name;
        p.Description = description;
        p.Quantity = quantity;
        p.Supplier = supplier;
       // p.VATRate = vatRate;
        p.ColorID = colorID;
        p.BrandID = brandID;
        p.Image = imagePath;
        //...
    }

非常感谢任何帮助

3 个答案:

答案 0 :(得分:1)

如果我愿意的话,我的方法是分开这两个,

  1. 为文本创建字符串数组
  2. 为值
  3. 创建字符串数组

    我认为值的数量与文本相同,因为它是动态生成的。

    然后在c#后端传递这两个字符串数组。

答案 1 :(得分:0)

你可以使用json2.js很酷,我用这个

var valueObj = { field1: $("input[name=field1]").val(),
                        field2: $("input[name=field2]").val()}

然后我可以解析:

JSON.stringify(valueObj)
在ajax调用中你可以像这样使用

$.ajax({
    type: "POST",
    url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
    data:valueObj ,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        alert("oh yeh");
    },
    error: function (error) {
        alert("An Error Occured");
    }
}); 

答案 2 :(得分:0)

00