Omeed
Omeed

Reputation: 53

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?

Upvotes: 2

Views: 2818

Answers (2)

FlowOverStack
FlowOverStack

Reputation: 1

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

Upvotes: 0

stambikk
stambikk

Reputation: 1365

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');

Upvotes: 1

Related Questions