SessionState
伺服器端函數中很可能需要訪問會話資訊。為此,只需要通過傳遞給Ajax.AjaxMethod屬性的一個參數告訴Ajax啟用這種功能。
在考察封裝器會話能力的同時,我們來看看其他幾個特性。這個例子中我們有一個文件管理系統,使用者編輯的時候會對文檔加鎖。其他使用者可以請求在文檔可用的時候得到通知。如果沒有AJAX,我們就只能等待該使用者再次返回來檢查請求的文檔是否可用。顯然不夠理想。使用支援工作階段狀態的Ajax就非常簡單了。
首先來編寫伺服器端函數,目標是迴圈遍曆使用者希望編輯的documentId(儲存在會話中)並返回所有已釋放的文檔。
[Ajax.AjaxMethod(HttpSessionStateRequirement.Read)]
public ArrayList DocumentReleased(){
if (HttpContext.Current.Session["DocumentsWaiting"] == null){
return null;
}
ArrayList readyDocuments = new ArrayList();
int[] documents = (int[])HttpContext.Current.Session["DocumentsWaiting"];
for (int i = 0; i < documents.Length; ++i){
Document document = Document.GetDocumentById(documents[i]);
if (document != null && document.Status == DocumentStatus.Ready){
readyDocuments.Add(document);
}
}
return readyDocuments;
}
}
要注意,我們指定了HttpSessionStateRequirement.Read值(還可以用Write和ReadWrite)。
現在編寫使用該方法的JavaScript:
<script language="javascript">
function DocumentsReady_CallBack(response){
if (response.error != null){
alert(response.error);
return;
}
if (response.value != null && response.value.length > 0){
var div = document.getElementById("status");
div.innerHTML = "The following documents are ready!<br />";
for (var i = 0; i < response.value.length; ++i){
div.innerHTML += "<a href=\"edit.aspx?documentId=" + response.value[i].DocumentId + "\">" + response.value[i].Name + "</a><br />";
}
}
setTimeout('page.DocumentReleased(DocumentsReady_CallBack)', 10000);
}
</script>
<body onload="setTimeout('Document.DocumentReleased(DocumentsReady_CallBack)', 10000);">
我們的伺服器端函數在頁面載入時調用一次,然後每隔10秒鐘調用一次。回呼函數檢查響應看看是否有傳回值,有的話則在div標籤中顯示該使用者可使用的新文檔。
結束語
AJAX技術已經催生了原來只有案頭開發才具備的健壯而豐富的Web介面。Ajax .NET封裝器讓您很容易就能利用這種新的強大技術。請注意,Ajax .NET封裝器和文檔仍在開發之中。 http://www.shpan.com/Detail.asp?ID=400