首页 > 解决方案 > 如何通过 JSON 将数组传递给 asmx Web 服务?

问题描述

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

设置删除文件

测试

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

这是我的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"));
    }
}

笔记

如果我将 astring作为没有数组的参数传递,它工作正常

标签: asp.netarraysjsonweb-services

解决方案


使用以下

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

并将输入参数数据类型更改List<string>string[]


推荐阅读