如何通过JSON将数组传递给Asmx Web服务?

时间:2018-10-22 11:30:01

标签: asp.net arrays json web-services

我想将数组值传递给我的Web服务文件。但这会引发以下错误

  

setDeleteFiles

     

测试

     

该测试表仅适用于以原始类型作为参数的方法。

这是我的jquery代码

$('#btnDeleteFiles').click(function () {
    var filesPaths = [];
    i = 0;
    $("input:checkbox[name=filed-checkedbox]:checked").each(function () {
        filesPaths[i] = $(this).val();
        i++;
    });

    //alert("filesPaths  =  " + filesPaths)
    var location = $('#ddlLocation option:selected').text();
    alert("Location = "+location)
    $.ajax({
        method: 'post',
        url: "GetAllFolderDetails.asmx/setDeleteFiles",
        data: {
            location: location,
            fileNames: filesPaths
        },

        dataType: "json",
        success: function (data) {
            window.location.reload(true);
            //alert("Success");

        },
        error: function (result) {
            alert("Error");
        }
    });
});

GetAllFolderDetails.asmx 代码

[WebMethod]
public void setDeleteFiles(string location, string[] fileNames)
{
    var locationID = 0;
    var domain = "domain";
    var username = "xxx";   //username
    var Password = "***";    //password

    Debug.WriteLine("Location = "+location);
    Debug.WriteLine("fileNames = " + fileNames);

    using (new ImpersonateUser(username , domain, Password))
    {
        Debug.WriteLine("Files names = "+ fileNames);
        foreach (string file in fileNames)
        {
            FileInfo files = new FileInfo(file);
            files.Delete();
        }
        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize("Files are successfully Deleted"));
    }
}

注意

  

如果我将string作为参数而不传递数组,则它工作正常

2 个答案:

答案 0 :(得分:0)

使用以下

data: JSON.stringify({ location: location, fileNames: filesPaths }),
contentType: "application/json; charset=utf-8",
dataType: "json",

,然后将输入参数的数据类型更改为List<string>,而不是string[]

答案 1 :(得分:0)

只需删除

 dataType: "json",
从您的Ajax调用中

。 并检查您的asmx文件是否已用

装饰
[System.Web.Script.Services.ScriptService]

尝试一下。