在ASP.NET中實現AJAX(三)

來源:互聯網
上載者:User
處理類型

 

返回複雜類型

Ajax封裝器不僅能處理ServerSideAdd函數所返回的整數。它目前還支援integers、strings、double、booleans、DateTime、DataSets和DataTables,以及自訂類和數組等基本類型。其他所有類型都返回它們的ToString值。

返回的DataSets和真正的.NET DataSet差不多。假設一個伺服器端函數返回DataSet,我們可以通過下面的代碼在用戶端顯示其中的內容:

<script language="JavaScript">

//Asynchronous call to the mythical "GetDataSet" server-side function

function getDataSet(){

AjaxFunctions.GetDataSet(GetDataSet_callback);   

}

function GetDataSet_callback(response){

var ds = response.value;

if(ds != null && typeof(ds) == "object" && ds.Tables != null){

var s = new Array();

s[s.length] = "<table border=1>";

for(var i=0; i<ds.Tables[0].Rows.length; i++){

s[s.length] = "<tr>";

s[s.length] = "<td>" + ds.Tables[0].Rows[i].FirstName + "</td>";

s[s.length] = "<td>" + ds.Tables[0].Rows[i].Birthday + "</td>";

s[s.length] = "</tr>";

}

s[s.length] = "</table>";

tableDisplay.innerHTML = s.join("");

}

else {

alert("Error. [3001] " + response.request.responseText);

}

}

</script>

Ajax還可以返回自訂類,唯一的要求是必須用Serializable屬性標記。假設有如下的類:

[Serializable()]

public class User{

private int _userId;

private string _firstName;

private string _lastName;

  public int userId{

get { return _userId; }

}

public string FirstName{

get { return _firstName; }

}

public string LastName{

get { return _lastName; }

}

public User(int _userId, string _firstName, string _lastName){

this._userId = _userId;

this._firstName = _firstName;

this._lastName = _lastName;

}

public User(){}

[AjaxMethod()]

public static User GetUser(int userId){

//Replace this with a DB hit or something

return new User(userId,"Michael", "Schwarz");

}

}

我們可以通過調用RegisterTypeForAjax註冊GetUser代理:

private void Page_Load(object sender, EventArgs e){

Utility.RegisterTypeForAjax(typeof(User));

}

這樣就可以在用戶端非同步呼叫GetUser:

<script language="javascript">

function getUser(userId){

User.GetUser(GetUser_callback);

}

function GetUser_callback(response){

if (response != null && response.value != null){

var user = response.value;

if (typeof(user) == "object"){         

alert(user.FirstName + " " + user.LastName);

}

}

}

getUser(1);

</script>

響應中返回的值實際上是一個對象,公開了和伺服器端對象相同的屬性(FirstName、LastName和UserId)。

http://www.shpan.com/Detail.asp?ID=398

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.