How to get individual parameters from a list of dynamic parameters in a web method submitted using jQuery ajax?

I am using the jquery ajax method on my aspx page, which will call the web method in the code behind. Currently, the web method accepts a couple of parameters, such as first name, last name, address, etc., which I pass from the jQuery ajax method using

data:JSON.stringify({fname:firstname,lname:lastname,city:city})

now my requirement has been changed so that the number and type of parameters to be passed are not fixed for the ex.parameter combination, maybe something like fname, city or fname, city or city, lname or fname, lname, city or something else. So the web method should be such that it accepts any numeric parameters. I was thinking about using arrays for this, as described here .

But I do not understand how I can determine which and how many parameters were passed to the web method for inserting / updating data in the database. Please can someone help me with this?

thank

+3
source share
4 answers

You can use a complex type on the client side that corresponds to an object on the server side that contains an array or several arrays of your parameters.

Very rude example

(server side)

//class declaration     
public class MyObject
{
      //values
      string[] Keys;
      string[] Values;

      //methods
      public void Add()
      {...} 
}

//web service - WebService.asmx
[WebMethod]
public void AddObject(MyObject NewObject)
{
     NewObject.Keys.Length = ...;
     NewObject.Add();
     ...
}

(client side)

var MyObject= { };

MyObject.Keys = { $("#key1").val(), $("#key2").val(), ... };
MyObject.Values = { $("#val1").val(), $("#val2").val(), ... };

var DTO = { 'MyObject' : MyObject};

$.ajax({
   type: "POST",
   contentType: "application/json; charset=utf-8",
   url: "WebService.asmx/AddObject",
   data: JSON.stringify(DTO),
   dataType: "json"
});

In the above example, your client-side object will be serialized, and you can access the server-side object in the same way as if you created it with new ().

+1
source

JSON -.

. , , , . , . , .

0

/:

var params = {};
if(city != null) {
    params.city = city;
}
params.fname = $("#fname").val();
...etc...

$.ajax({
    ...
    data:JSON.stringify(params);
    ...
});
0

webmethod (, )

Thus, when you receive a request to the server, you first split it into "," to get an array of pairs of name values, and then split each pair to get separate names and values.

Keeps a simple call, and you can handle it with complex code on a server with fluffy intellisense .NET frameworks to help you.

KISS = Keep It Simple Stupid

My old music teacher lived this way, I just realized why recently !!!!

0
source

Source: https://habr.com/ru/post/1745097/


All Articles