passing complex structure from client to webservice
My webservice gets an item and should store it and it's fields:
[WebMethod]
public void StoreItem(Item item)
{
item.Store();
}
There are 4 types of fields but when the client pass the Item object - the fields will not pass correctly since it is an interface and not implementation. One possible solution - which not help me at all is to use instead the following webservice:
[WebMethod]
public void StoreItem(Item item, frstTypeField[] fields12, scndTypeField[] fields,
thrdTypeField[] fields3, frthTypeField[] fields4)
{
//append fields to item and then store
}
I don't like this solution开发者_StackOverflow社区 because I need to change the webservice when I add a new field type. In addition - Item is part of an order so there is another webservice that stores an order. So how can I pass the fields for each item in the order?
Is there any solution for this?
You'll need to make all relevant information public properties and also make sure all of them are xml serializeable (or provide custom serialization via the IXmlSerializable
interface).
I got this working by sending in a JSON object to my WebMethod with a __type
property equal to the qualified class (e.g. {item:{'__type':'MyNamespace.Item'}}
.
But that can be a bit tedious if your Item
object is somewhat complex.
What I did to start is to publish a WebMethod
that takes no parameters, and just returns a newly instantiated object of whatever type I wanted to pass in to my real WebMethod
.
[WebMethod]
public static Item GetItem () {
return new Item {
// set properties, whatever
};
}
Call that from your jQuery, and use something like JSON2 to inspect the returned object.
$(function() {
$.ajax({
url : 'default.aspx/GetItem',
data : '{}',
// blah
success : function (m) {
alert (JSON.stringify(m.d));
}
});
});
... then just use the resulting JSON string as a template. Modify as needed.
My answer: I made a transition object named "TransitionItem" which holds 4 properties where each property is an array with type of one of the fields types. Within this transition object I created method called ToItem that "translates" the TransitionItem to a "normal" Item with all the interfaces and stuff. So my webservice now looks like:
[WebMethod]
public void StoreItem(TransitionItem tItem)
{
IItem item=tItem.ToItem();
item.Store();
}
This is how I solved it.
精彩评论