如何将 javascript 对象以 C# 对象作为参数传递到 C# Web 服务中

问题描述 投票:0回答:2

所以基本上我有一个 C# Web 方法,我将通过 ajax 调用它。 C# 参数是一个简单的 KeyValue 对象,如下所示:

public class KeyValue
{
    public string Key { get; set; }
    public string Value { get; set; }
}

在我的 JavaScript 中,我创建了一个具有键值对结构的哈希。

var updateSettingsHash = [];

这是它初始化的地方,然后我稍后使用 .Add 添加到它,并遵循数组的键/值格式(因此它的作用就像字典)。

所以我现在的问题是,我有一个接受参数列表的 C# webmethod

[WebMethod]
    public ServiceResult SaveConfigurationValuesForPrivateLabel(List<KeyValue> settings)

确实有两个问题。 A) 如何使用 ajax 传入 List?因为javascript中没有列表? B) 如何在 javascript 中使用 KeyValue 类来创建实例并能够创建它们的列表?

javascript asp.net ajax
2个回答
1
投票

您可以创建一个 javascript 对象数组,并使用例如 jquery 调用 webmethod,如下所示:

var settingsList= [{Key: 'a', Value: 'A'}, {Key: 'b', Value: 'B'}, {Key: 'c', Value: 'C'}];
var jsonText = JSON.stringify({ settings: settingsList});

$.ajax({
  type: "POST",
  url: "WebService1.asmx/SaveConfigurationValuesForPrivateLabel",
  data: jsonText,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function() { alert("it worked"); },
  failure: function() { alert("Something's wrong"); }
});

至于在 javascript 中直接使用 C# 类,我认为不可能,您可以使用如上所示的匿名对象,也可以创建如下所示的对象原型:

function KeyValue(Key, Value){
   this.Key = Key;
   this.Value = Value;
}

var keyValuePair = new KeyValue('x', 'X');

0
投票

这对我有用:

Javascript-客户端:

    function Car (name, model, year) {
        this.name = name;
        this.model = model;
        this.year = year;
    }
                    
    function Test51 () {
        const myCar = new Car("Name", "Model", 1903);
                    
       /* add extra wrapper name 'car' - the parameter name of the C# webservice method */
        const payload = { car: myCar };
        Fetch('Test51', "POST", payload, Callback51);
    }

    function Test52 () {
       const myCars = [ new Car("Name 1", "Model 1", 1993), new Car("Name 2", "Model 2", 1961) ];

       /* add extra wrapper name 'cars' - the parameter name of the C# webservice method */
       const payload = { cars: myCars };
       Fetch('Test52', "POST", payload, Callback52);
    }
                        
    async function Fetch(uri, httpType, payload, callBackFunc) {
                        
        uri = "Service.asmx/" + uri;
        wait fetch(uri, {
        method: httpType,
        headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload)
        }).then(async function (rawResponse) {
            
            switch (rawResponse.status) {
                  case 200:
                       const response = await rawResponse.json();
                       callBackFunc(response);
                       break;
                  case 401:
                      
                       break;
                  default:
                                    
                       break;
                            }
       }).catch(function (error) {
           console.log(error);
       });
   }
         
   function Callback51 (response) {
        console.log(response);
   }
   
   function Callback52 (response) {
        console.log(response);
   }

C#-WebService (*.asmx)

    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class Service : System.Web.Services.WebService
    {
        [WebMethod]
        public string Test51(Car car)
        {
            return "OK";
        }

        [WebMethod]
        public string Test52(List<Car> cars)
        {
            return "OK";
        }
    }

    [Serializable()]
    public class Car
    {
        public string Name { get; set; }
        public string Model { get; set; }
        public int Year { get; set; }
    }
© www.soinside.com 2019 - 2024. All rights reserved.