将 JavaScript 对象反序列化为 C# 处理程序中的泛型列表

Deserialize javascript objects to generic list in c# handler

本文关键字:程序 泛型 列表 处理 JavaScript 对象 反序列化      更新时间:2023-09-26

>我在循环中创建一些javascript项

var licenseList = {};
$($licenses).each(function (index) {
                var license = {};
                var editedValues = {};
                license.PRODUCT_KEY = $(this).parent('div.licensewrapper').data('productkey');
                $(this).find('input:text').each(function (i, val) {
                    if ($(val).attr('data-default-value') != $(val).val() && $(val).val() > 0 && $(val).data('isValid') != false) {
                        var pogKey = $(val).data('product_option_group_key');
                        var editedValue = $(val).val();
                        editedValues[pogKey] = editedValue;
                        license.editedValues = editedValues;
                    }
                });
    //licenseList[index] = license;
    //liceneList.push(license); //if array...
});

我已经注释掉了我当前的解决方案。但是我认为在 c# 中对它们进行去化时,两者中的任何一个都不等于泛型列表。在这种情况下,有什么合适的方法可以做到这一点?谢谢

创建数组

var licenseList = [];

对于您的每个许可证...

var license = {
    prop1: 'p1',
    prop2: 'p2'
};
licenseList.push(license);

格式化和序列化要发送到 WebMethod 的 JSON 数据

data = {
    LicenseList: licenseList
};
$.ajax({
      ...
      data: JSON.stringify(data)
      ...
      });

在 WebMethod 中,您的方法参数必须匹配

[WebMethod]
public static string GetLicenses(List<License> LicenseList)
{
   foreach(var license in LicenseList)
   {
     // do whatever
   }
}

示例许可证类。您的属性需要与 JavaScript 中的对象匹配

public class License
{
   public string Prop1 {get; set;}
   public string Prop2 {get; set;}
}

希望这有帮助。

  function sendToServer(licenseList)
  {
  var url = "controller.ashx";
  var data = {};
  data.SerializedObj = JSON.stringify(licenseList);
   $.post(url, data, function(response){
    if(response.length > 0)
    {
        alert(response);
    }
   });
  }
  //controller.ashx :
  public void ProcessRequest (HttpContext context) {
  //...
  string serializedObj = context.Request.Form["SerializedObj"] ?? "";
  JavaScriptSerializer js = new JavaScriptSerializer();
  List<license> collection = js.Deserialize<List<license>>(serializedObj);
  //...
  public class license
  {
  public  string Propertie1 {get;set;}
  public  string Propertie2 {get;set;}
  }

Javascript 对象必须具有相同的属性:

var license = {Propertie1 : 'value1', Propertie2 : 'value2'};