18. July 2010 22:26 by Jerry in
Old blog posts Suppose you have following function in your project:
C# Code:
Code
1
2
3
4
5
6
7
8
9
10
|
public void MessageBox(string msgText){string scriptKey = "Message";if (!ClientScript.IsStartupScriptRegistered(scriptKey)){ClientScript.RegisterStartupScript(this.GetType(), scriptKey, "<script>alert('" + msgText + "')</script>");}} |
VB Code:
Code
1
2
3
4
5
6
7
8
9
10
11
|
Protected Sub MessageBox(ByVal strMsg As String)Dim key As String = "Message"If Not ClientScript.IsStartupScriptRegistered(key) ThenClientScript.RegisterStartupScript(Me.GetType(), key, "<script>alert('" + strMsg + "');</script>")End IfEnd IfEnd Sub |
This function is to show a client-side message box by using javascript. You might utilize this function like this:
C# Code:
Code
1
2
3
4
5
6
7
8
9
|
protected void btnSearch_Click(object sender, EventArgs e){......code omitted MessageBox("Search completed!");} |
VB Code:
Code
1
2
3
4
5
6
7
8
9
10
|
Protected Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click......code omittedMessageBox("Search completed!")End Sub |
The code above has no problem at all if not using AJAX. With Ajax extension however, the button "btnSearch" will be placed inside an UpdatePanel control to avoid the page being post-back. The MessageBox will not work as normal any more afterward. In such case, you might need to do some extra work on the MessageBox method.
C# Code:
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public void MessageBox(string msgText){string scriptKey = "Message";if (ScriptManager.GetCurrent(this.Page)!=null && ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack {ScriptManager.RegisterStartupScript(this, this.GetType(), scriptKey , "alert('" + msgText+ "');", true);}else {if (!ClientScript.IsStartupScriptRegistered(scriptKey)){ClientScript.RegisterStartupScript(this.GetType(), scriptKey, "<script>alert('" + msgText + "')</script>");}}} |
VB Code:
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
Protected Sub MessageBox(ByVal strMsg As String)Dim key As String = "Message"If ScriptManager.GetCurrent(Me.Page) IsNot Nothing AndAlso ScriptManager.GetCurrent(Me.Page).IsInAsyncPostBack Then'to support ajax post back ScriptManager.RegisterStartupScript(Me, Me.GetType(), key, "alert('" + strMsg + "');", True)Else'normal callIf Not ClientScript.IsStartupScriptRegistered(key) ThenClientScript.RegisterStartupScript(Me.GetType(), key, "<script>alert('" + strMsg + "');</script>")End IfEnd IfEnd Sub |
Simply use RegisterStartupScript from ScriptManager (System.Web.Extension.dll) to generate javascript code instead of that from Page object.
Hope you enjoy with ASP.NET AJAX again!