javascript - 如何在ajax中构建字符串数组并将其传递给asp?

标签 javascript c# asp.net ajax

在我的项目中,我想使用ajax来进行JS和ASP之间的通信。但是,我得到了 500 错误。

JS ajax 中的 JSON 字符串:

 {lists: [{'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a111', 'colour': 'red'}, {'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a222', 'colour': 'green'}]}

C#:

 [WebMethod]
 public static string GetCurrentTime(List<string> lists)
 {
     return "text string" ;
 }

完整的 AJAX:

var dataJson = "{lists: [{'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a111', 'colour': 'red'}, {'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a222', 'colour': 'green'}]}";
     $.ajax({
            type: "POST",
            url: URL,
            data: dataJson ,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
function OnSuccess(response) {
        console.log(response.d);
    }

最佳答案

尝试使用JSON.stringify如下所示,用一个对象代替 List<string> ,

var dataJson = {lists: [{'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a111', 'colour': 'red'}, {'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a222', 'colour': 'green'}]};
     $.ajax({
            type: "POST",
            url: URL,
            data: JSON.stringify(dataJson),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
function OnSuccess(response) {
        console.log(response.d);
    }

C#

public class Data { 
        public string ID {get;set;}
         public string colour {get;set;}   // This can be renamed into Pascal case here and in the json
       }

[WebMethod]
 public static string GetCurrentTime(List<Data> lists)
 {
     return "text string" ;
 }

关于javascript - 如何在ajax中构建字符串数组并将其传递给asp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40414999/

相关文章:

javascript - Firebase 电话身份验证 : Is it possible to only check if the telephone exists in Authentication and not Sign Up the user automatically?

javascript - 设置最大字数 HTML 文本框

javascript - 工具提示始终显示相同的值

Javascript 未捕获类型错误 : Cannot read property '0' of undefined

c# - 如何将 CheckBox 添加到 TemplateField HEADER?

asp.net - 配置文件 XDT 转换 InsertIfMissing 正在跳过子项

asp.net - ReportViewer 2012 是否与用于远程访问的 SSRS Server 2005 兼容?

c# - Entity Framework - SQL Azure 重试策略

c# - .NET MVC Fire and Forget Method 也立即返回 View

c# - Entity Framework : Generate custom Id for MYSQL table