简体   繁体   中英

How to pass javascript object into c# web service with c# object as a parameter

So basically I have a C# web method that I will call via ajax. The C# paramter is a simple KeyValue object, that looks like this:

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

and in my javascript I have created a hash that has a key value pair structure.

var updateSettingsHash = [];

this is where it's initialized, and then I add to it later using .Add, and following a key/value format for the array (so it's acting like a dictionary).

So my question is now, I have a C# webmethod that accepts a parameter List

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

So really 2 questions. A) How do I pass in a List using ajax? Since there is no lists in javascript? and B) How do I use the class KeyValue in javascript to create instances and be able to create a list of them?

You can create an array of javascript objects and using for example jquery call the webmethod like this:

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"); }
});

As for directly using a C# class in javascript, I don't think it's possible, you can either use anonymous object like shown above or create an object prototype like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM