Implementing dialog box in ASP.NET based web application

Note: This is rewrite of an article which I have published on DotNetJunkies.com in 2003

Introduction
Implementing dialog box in the application is some time very critical in order to have close talks between user and the application without shifting current user interfgace context on the page..

Dialog box is commonly used to give some kind of feedback to the user or to receive input from the user or even both.

Implementing a dialog box in windows based application is simple.

Dim fChild As New frmChild  
frmChild.Show vbModal

But how about implementing the same dialog box in web based application? In the following article, we will discuss some of techniques of implementing a dialog box in web based application.

Simple Dialog Box
More common technique of implementing dialog box is to put JavaScript alert function to the particular event (usually onClick event) of the control. It very basic implementation when your application already aware when to open a dialog box at the page loads to the browser.

Following is the simple example. Place a button in the form control of the web page and insert the following code.

btnOpen1.Attributes.Add("onclick", "alert('GOT IT?');") It’s one line code to pop a alert message to the user.

Similarly, you can use same implementation to open a confirmation dialog box, where user can pick his/her option. It's common implementation where application is about to delete a record and what to get confirmation from the user before processing the request. Let's open a confirmation dialog box for the delete button in the following example. Implementation will be something like following:

btnDelete.Attributes.Add("onclick", "if(confirm('Are you sure to delete?')){}else{return false}")

Above server side code will generate a Javascript code attached to the onClick event of the button. When user select "No" in the confirmation dialog box, code will return false and nothing will happen. But if user selects "Yes", code will return true and code will post the page.

Now, let's discuss more compldex senerios after basic implementation.

Opening dialog box with other web page In this exmaple we will see how we can open a web page as a dialog box. Implementation will remain same except a slight modification:

btnOpen2.Attributes.Add("onclick", "window.open ('child.aspx')")

btnOpen is a button control and when user click on this button, it will open another browser windows with Url pointing to "child.aspx".

Above implementation works fine, except code will open another instance of the browser in your task bar which sometime bit annoying to the users.

How about opening same page with modal dialog box? Following is the implementation:

btnOpen3.Attributes.Add("onclick", "window.showModalDialog('child.aspx', null,'status:no;dialogWidth:370px; dialogHeight:220px;dialogHide:true;help:no;scroll:no');")

Above code will generate a small JavaScript code attached to the onClick event of the button btnOpen3.

If you inspect the rendered html code carefully for above examples, you will find what you want to know. Following are the rendered html code which are generated through above dialog box popup examples.

<input type="submit" name="btnOpen1" value="Open 1" id="btnOpen1" onclick="alert('GOT IT?');" style="width:64px;Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 8px" />

<input type="submit" name="btnDelete" value="Delete" id="btnDelete" onclick="if(confirm('Are you sure to delete?')){}else{return false}" style="width:64px;Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 48px" />

<input type="submit" name="btnOpen2" value="Open 2" id="btnOpen2" onclick="window.open('child.aspx')" style="width:64px;Z-INDEX: 103; LEFT: 8px; POSITION: absolute; TOP: 88px" />

<input type="submit" name="btnOpen3" value="Open 3" id="btnOpen3" onclick="window.showModalDialog('child.aspx',null,'status:no;dialogWidth:370px; dialogHeight:220px;dialogHide:true;help:no;scroll:no');" style="width:64px;Z-INDEX: 104; LEFT: 8px; POSITION: absolute; TOP: 128px" />

Returning value from dialog box
Now lets discuss returning value from a dialog box. Let say, you have a dialog box and you want to return a value from this dialog box to the parent form/page.

To return any value from child dialog box to the parent window form, Javascript provides an attribute in the window object, which is:

window.returnValue

To understand how returnValue property works, let's create a small web project with two web forms with following name:

parent.aspx
child.aspx

Parent web form will have a textbox and a button. Following are the parent HTML code:

parent.aspx

<body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
    <asp:TextBox id="txtValue" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px" runat="server"></asp:TextBox>
    <asp:Button id="btnOpen" style="Z-INDEX: 102; LEFT: 176px; POSITION: absolute; TOP: 24px" runat="server" Text="Open..."></asp:Button>
  </form>
</body>

parent.aspx.vb

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  btnOpen.Attributes.Add("onclick", "var strReturn; strReturn=window.showModalDialog('child2.aspx',null,'status:no;dialogWidth:370px; dialogHeight:220px;dialogHide:true;help:no;scroll:no');if (strReturn != null) document.getElementById('txtValue').value=strReturn;")
End Sub

And, following is the child web form which will have a textbox and two buttons:

child2.aspx

<body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
    <asp:TextBox id="txtValue" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px" runat="server"></asp:TextBox>
    <asp:Button id="btnOK" style="Z-INDEX: 103; LEFT: 48px; POSITION: absolute; TOP: 56px" runat="server" Text="Ok" Width="56px"></asp:Button>
    <asp:Button id="btnCancel" style="Z-INDEX: 102; LEFT: 112px; POSITION: absolute; TOP: 56px" runat="server" Text="Cancel"></asp:Button>
  </form>
</body>

child2.aspx.vb

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  btnOK.Attributes.Add("onclick", "window.returnValue = document.getElementById('txtValue').value; window.close();")
btnCancel.Attributes.Add("onclick", "window.close();")
End Sub

The basic flow of above implementation is that when user clicks on the button of parent form, code will open child.apsx file in a dialog box. In the child form, user will then enter some value in textbox and clicks on the Ok button, which will return control to the parent form. With that, it will also update the value of textbox in parent form. And of course, if user clicks on Cancel button instead, code will simply close the child dialog box without doing anything.

NOTE: You will face an issue when user click on any button in the child page, which is opened using showModalDialog function. When user click on that button, it will open another instance of the browser instead. This is issue with using showModalDialog function. To address this issue, simply place a <base target="_self"> inside the HEAD element of the child window. This will not let browser to open another instance of browser.

In all of the above examples, there is no involvement of ASP.NET. All flows are actually handled by the JavaScript code. Review the JavaScript code of the child web form. <input name="txtValue" type="text" id="txtValue" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px" />

<input type="submit" name="btnOK" value="Ok" id="btnOK" onclick="window.returnValue = document.getElementById('txtValue').value; window.close();" style="width:56px;Z-INDEX: 103; LEFT: 48px; POSITION: absolute; TOP: 56px" />

<input type="submit" name="btnCancel" value="Cancel" id="btnCancel" onclick="window.close();" style="Z-INDEX: 102; LEFT: 112px; POSITION: absolute; TOP: 56px" />

In the child web form, value which we want to return is assigned to the window.returnValue which is then assigned to a variable in parent web form, which is further assigned to textbox.

To summarise the implementation, window.returnValue returns a value from child window to parent window and you can do anything with that returned value in parent page.

One thing you must have notice that I have used Response object to close the dialog box. Passing JavaScript snippet to the response object is another way to embed JavaScript to the web form. In above code it create a script, which contains window.close() statement, and it embedded into the page. At the client side of browser, browser will read the script and execute it.

In last example, we learnt a another way to embed JavaScript in page and that is using response object. Yes, you can also use response object to popup an alert message as well. Here is the code for that:

Private Sub btnOpen5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen5.Click
  Dim strScript As String = ""
  strScript = "<script>"
  strScript = strScript & "alert('Simple alter message!!!!');"
  strScript = strScript & "</script>"
  Response.Write(strScript)
End Sub

Above code will pop up an alert message to user when user hit btnOpen5 button.

If you want to display a variable instead as a message in the alert message then you can modify same code as following:

Private Sub btnOpen6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen6.Click
  Dim strScript As String = ""
  Dim intSum As Integer
  strScript = "<script>"
  intSum = 344 + 233
  strScript = strScript & "alert('SUM : " & intSum & "');"
  strScript = strScript & "</script>"
  Response.Write(strScript)
End Sub

There is one drawback with above code to pop up alert box. You will learnt it if you try above code on your machine. We will talk about it later in the article.

Same implementation can be done by registering JavaScript code to the browser as well. Following example is doing same thing but we are registering the JavaScript to the web page.

Private Sub btnOpen7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen7.Click
  Dim strScript As String = ""
  strScript = "<script>"
  strScript = strScript & "alert('Simple alter message!!!!');"
  strScript = strScript & "</script>"
  Page.RegisterClientScriptBlock("ClientScript", strScript)
End Sub

Have you discovered the drawback? Yes, it will left screen of the parent page blank after showing alert message or dialog box. User will see a blannk page with dialog box open and content of the page will only display to the user after user close that alert message or dialog box.

The reason of blank page is because JavaScript is generated at the top of html page. You can easily understand the issue if you inspect the generated html code of the page using View Source. Following is the rendered HTML code:

This code is generated using Response object:

<script>alert('Simple alter message!!!!');</script>
<HTML>
<HEAD>
  <title>WebForm1</title>
</HEAD>
<body MS_POSITIONING="GridLayout">
</body>
</HTML>

Code generated using RegisterClientScriptBlock method:

<HTML>
<HEAD>
<title>WebForm1</title>
</HEAD>
<body MS_POSITIONING="GridLayout">
  <form name="Form1" method="post" action="MainForm.aspx" id="Form1">
    <script>alert('Simple alter message!!!!');</script>
  </form>
</body>
</HTML>

In the last example, Javascript snippet is rendered just below the form tag, but still it's placed above all of the html and web controls. And when an alert message or a modal dialog box is opened, control will gone to the opened dialog box and rest of the controls will not displayed as they are not yet rendered on the page. When user closes the alert message, control return back to the page and rest of the controls rendered.

To rendered all controls of the page while still showing an alert message or dialog box, you can use RegisterStartupScript method instead. Let's review the rendered HTML code generated using RegisterStartupScript:

<HTML>
<HEAD>
  <title>WebForm1</title>
</HEAD>
<body MS_POSITIONING="GridLayout">
  <form name="Form1" method="post" action="MainForm.aspx" id="Form1">
    <script>alert('Simple alter message!!!!');</script>
  </form>
</body>
</HTML>

Generated JavaScript is placed just above the closing tag of the form but below html or web controls tags. In this case, all html controls will render first on the browser and thereafter modal dialog box or modal dialog box will open for the user.

Conclusion
Implementing dialog box in web based application makes your application more usable and interactive. It will further help your application to have dialogs with the user more closely.