问题
I'm relatively new to utilizing web services. I'm trying to create one that will be accepting data from a ASP.Net form whose input controls are created dynamically at runtime and I don't how many control values will be getting passed.
I'm thinking I'll be using jQuery's serialize() on the form to get the data, but what do I have the web service accept for a parameter? I thought maybe I could use serializeArray(), but still I don't know what type of variable to accept for the JavaScript array.
Finally, I was thinking that I might need to create a simple data transfer object with the data before sending it along to the web service. I just didn't wanna go through with the DTO route if there was a much simpler way or an established best practice that I should follow.
Thanks in advance for any direction you can provide and let me know I wasn't clear enough, or if you have any questions.
回答1:
The answer to the headline question (assuming this is an ASP.Net web service) is to use the params
keyword in your web service method:
[WebMethod]
public void SendSomething(params string[] somethings)
{
foreach (string s in somethings)
{
// do whatever you're gonna do
}
}
Examples:
SendSomething("whatever");
SendSomething("whatever 1", "whatever 2", "whatever 3");
In fact, you don't really even need the params
keyword - using an ordinary array as a parameter will let you pass in an unknown number of values.
回答2:
Well I went with creating my own data transfer object which I guess was always the front of brain solution, I was just thinking that there was probably a recognized best practice on how to handle this.
来源:https://stackoverflow.com/questions/2730482/passing-a-web-service-an-unknown-number-of-parameters