Wednesday, June 3, 2009

Show MessageBox in the Browser in ASP .NET 2.0 using AJAX

AJAX is a good technology that increases the performance of Web Application while executing server side code in a form on the client side in ASP.Net 2.0. You can use the AJAX tools in ASP.NET 2.0 to create JavaScript from the server and execute it on the client.

Presently I am working on a Project. We developed our application in ASP.NET 2.0 without AJAX. Later on at the time of testing we found that there are lots of postbacks in a page to validate the data entered by the user. So we have to implement AJAX in the current application to reduce the full page postbacks with partial page postbacks.

We used ScriptManager and UpdatePanel controls on the pages along with changes in the web.config for AJAX to work. Use of UpdatePanel helped the application to reduce the complete page postbacks with partial page postbacks.

At some places, after validating the data entered by user from the server, we are to show message box to the user indicating the problem with the data entered. We originally achieved that using JavaScript alert in our application because inbuilt function msgbox is not working after publishing ASP.NET 2.0 Web Application on WebServer.

After the use of UpdatePanel, these Javascript alerts also failed to show message to the user. When you are working inside an update panel, you need to exercise a method of the ScriptManager in order for your javascript to work.

I created the following procedure which can be called from the code inside the update panel, where you want to show a javascript alert. This procedure is to help me to utilize the ScriptManager to execute javascript from the server:

Public Sub rkShowAJAXMessageBox(ByVal msg As String)
Dim rkMsg As String = String.Format("alert('" & msg & "')")
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "rkMsg", rkMsg, True)

End Sub


You are to pass in the Message String you want to show in the Javascript Alert and the job is done for you.


So for example, in your code behind file, you created the above procedure and just give a call to this procedure with a Message String as parameter to show:

rkShowAJAXMessageBox("Invalid User ID/Password")

Here come the desired results of showing MessageBox to the user, just by calling rkShowAJAXMessageBox method in the code behind file when you .aspx page is using the update panels.



No comments: