【发布时间】:2011-12-19 13:58:09
【问题描述】:
我正在使用 JQuery 和 ajax 调用一个 asp.net 网络服务,使用 json 传输数据。 我正在创建将被 json 字符串化的 javascript 对象。我需要我的 web 方法来检索这些特定的对象类型,但我的参数类型是一个基类,并且这些对象从我的基类继承,如下所示:
[DataContract]
[KnownType(typeof(TextareaObject))]
[KnownType(typeof(TextObject))]
public class FormElement
{
public FormElement()
{}
}
和:
[DataContract(Name = "textObject")]
public class TextObject : FormElement
{
[DataMember]
public string question { get; set; }
public TextObject(string question)
{
this.question = question;
}
}
和我的网络方法:
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
[OperationContract]
[ServiceKnownType(typeof(TextObject))]
[ServiceKnownType(typeof(TextareaObject))]
public void SaveForm(List<FormElement> formobjects)
{
...
}
这就是我创建 javascript 对象的方式(我只复制我的代码的相关示例):
//objects to serialize
function textObject(question) {
this.question = question;
}
//objects to serialize
function textareaObject(question, rownumber) {
this.question = question;
this.rownumber = rownumber;
}
var objectarray = new Array();
if (type == 'text') {
textobject1 = new textObject(typedquestion);
objectarray.push(textobject1);
}
else if (type == 'textarea') {
var rownumber = $(elm).children('textarea').attr('rows');
textareaobject1 = new textareaObject(typedquestion, rownumber);
objectarray.push(textareaobject1);
}
var formobjects = JSON.stringify(objectarray);
$.ajax({
type: "POST",
//Page Name (in which the method should be called) and method name
url: urlhtml,
data: '{"formobjects":' + formobjects + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//dosmth
}
});
我希望 asp.net 服务器能够反序列化我的数组中的正确类型。 但是一旦在我的 webmethod 中,“formobjects”都是 FormElement 类型,即使使用 serviceknowntype 属性,我也无法获得它们的真实类型。是因为 javascript 不是强类型,我无法检索具体类型吗?因为字符串化的 json 不会给出具体的类型? 我试过了
textObject.prototype = new textObject(typedquestion);
objectarray.push(textObject.prototype);
并且 json 给出了类似的东西:
{"formobjects":{"textObject": {"question":"test"}}}
但是服务器端同样老旧,我的 webmethod 中只有 FormElement 类型,我无法转换。
也许我想做的事情是不可能的.. 还是谢谢你!!
【问题讨论】:
标签: jquery asp.net wcf deserialization datacontract