我想在aspx頁面的客戶端創建對象。我想爲這些JavaScript類添加功能以使生活更輕鬆。使用JQUERY ajax函數發送JSON對象到ASP.NET Web服務
其實我可以得到並使用從服務返回的對象(派生自服務器端類)。當我想的jQuery AJAX方法來發送來自客戶端的對象,我不能這樣做:)
這是我的JavaScript類:
function ClassAndMark(_mark, _lesson){
this.Lesson = _lesson;
this.Mark = _mark;
}
function Student(_name, _surname, _classAndMark){
this.Name = _name;
this.SurName = _surname;
this.ClassAndMark = _classAndMark;
}
這是學生類的方法來調用Web服務:
JSClass.prototype.fSaveToDB(){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/WS/SaveObject.asmx/fSaveToDB"),
data: ????????????,
// This might be: JSON.stringify(this) ?
// Web service method has a parameter, name is _obj
// if i don't send data with parameter, i'm getting this error:
// Invalid web service call, missing value for parameter: '_obj'
//
// Should i send it like that:
// data: "{_obj:" + JSON.stringify(this) + "}"
//
// I tried to wrap this with parameter like that:
// data: JSON.stringify("{_obj:" + this + "}")
//
// But i got this error:
// Cannot convert object of type 'System.String' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'
dataType: "json"
});
}
創建JavaScript對象,並調用它的方法來發送它向Web服務:
其實我不知道應該是什麼的類和方法定義S於服務器端,但我認爲:
class ClassAndMark{
public string Lesson ;
public string Mark ;
}
class Student{
public string Name ;
public string SurName ;
public ClassAndMark classAndMark ;
}
Web服務是低於但我又不能得到應該的,而不是什麼???? :
[WebMethod()]
public Student fSaveToDB(???? _obj)
{
// How can i convert input parameter/parameters
// of method in the server side object?
// SQL operations
// srting QInsert = "INSERT INTO tableName (......) VALUES (.....)";
// ...
// ..
// .
return new Student{
Name = ???, // deserialize _obj and pass its Name value
SurName = ???, // deserialize _obj and pass its SurName value
classAndMark = ???, // deserialize _obj and pass its classAndMark value
};
}
這不工作「數據:JSON.stringify(myObj)」,因爲Web服務方法有參數名稱,它給出了錯誤,如「你沒有用這個參數調用我」... – uzay95 2010-04-15 14:17:42
你試過包裝你的對象,就像我在最後一行寫的那樣? 像這樣:data:JSON.stringify({paramName:myObj}) – mamoo 2010-04-15 14:28:20
我試過並得到這個錯誤:無法將類型'System.String'的對象轉換爲類型'System.Collections.Generic.IDictionary'2 [System.String ,System.Object]' 你有什麼想法嗎?並感謝您的幫助... – uzay95 2010-04-15 14:45:39