2

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?

3
  • The list can be represented with an anonymous object in javascript ( var list = [ { Key = "ABC", Value = "DEF" }, { Key = "ZZZ", Value = "YYY" } ]; ). Then, serialized as json for transmitting to asp.net Commented Apr 3, 2015 at 16:18
  • Ok, makes sense, but still trying to figure out how to pass in C# classes into javascript ajax call. Commented Apr 3, 2015 at 16:20
  • See if my answer on this question helps you at all. It's a little more in-depth than what you are looking for, but should get you on the right track. Let me know if you have any more questions after, and I'll do my best to help. Commented Apr 3, 2015 at 16:41

2 Answers 2

1

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');
Sign up to request clarification or add additional context in comments.

Comments

0

This works for me:

Javascript-Client:

    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, CallbackTest51);
    }

    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, CallbackTest52);
    }
                        
    async function Fetch(method, httpType, payload, callBackFunc) {
                        
        var uri = "Service.asmx/" + method;
        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 CallbackTest51 (response) {
        console.log(response);
   }
   
   function CallbackTest52 (response) {
        console.log(response);
   }

C#-WebService (Service.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; }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.