27 Apr 2006

Implementing dialog box in ASP.NET based web application

13 Comments ASP.NET

Note: This is rewrote of an article which I have published three years back in DotNetJunkies.com

Introduction
Using dialog box in any application is very important in order to provide close talks between user and application. These dialogs greatly enhance the usability of application.

Dialog box usually can be used to give some kind of feedback to user or to get some input from the user or even both which does require to display/change whole UI.

It was really a kid’s work to implement any dialog box in the window based application. Yes! It was very simple

Dim fChild As New frmChild
frmChild.Show vbModal

How easy it was??? But, how about opening the same kind dialog box in web based application? Oops! Its does require some hacking to open it, especially if you want to open a modal dialog box.

In the following article, we will see some of the important techniques of implementing dialog box in the web based application.

Simple Dialog Box
The first and usual technique of implementing dialog box is to put JavaScript to particular event (usually onClick event) of the control. It’s really easy way when your application already know when to open a dialog box when the page loads to the browser.

Here is the simple example, put a button form control to 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.

Same way, suppose you want that, application opens a confirmation dialog box from where user can select his options. You can use this method very well in this scenario. Suppose, you want to open a confirmation dialog box when user clicks on delete button of page. Simply use following code for that:

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

It will generate a small JavaScript code to the browser. When user select “No” from the confirmation dialog box, it will return false. Hence nothing will happen. And if user selects “Yes”, it will return true and will post that page.

Ok. After little bit of simple alert and confirmation dialog box, we will now enter into some serious work of opening dialog box.

Opening dialog box with other web page
Suppose, you want to open another web page as a dialog box, then what will you do?

Here is the same code with little difference.

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

btnOpen is a button control and when user clicks on this button, it will open another instance of browser with page “child.aspx”.

It’s really working well, until you will notice that it do open another instance of browser, and so put another application in task bar, with that even the opened dialog box is modeless. Is it not possible to open a page in the same browser with modal dialog box? Sure! Here is the code for that:

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

What does above code actually do? Nothing! It simply creates a small JavaScript code to the page and attach the click event of the control to that script. If you look at the rendered html code of page, you will find what you want to know. Here is that rendered html code which is generated through above dialog box popup.

<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
Ok! How about returning value from opened dialog box? Suppose you have open a dialog box and you want to return a value from the child window to parent form.

For returning any thing to the parent window from the child dialog box, JavaScript do provides an attribute in window object, which is

window.returnValue

To understand how its work, lets 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. Look at the following code of the parent web form.

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, child web form which will have a textbox and two buttons. Look at the following code of the child page.

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 objective of this module is that when user clicks on the button of parent form, it will open child.apsx file in dialog box. In child form, user will enter some value in textbox and clicks on the Ok button which will return 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, it will simply close the child dialog box without doing anything.

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

In all of the above scenarios, there is nothing involved ASP.NET. All of stuff are actually handled by JavaScript code. See the JavaScript code of 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 child web form, the value which we want to return is assigned to the window.returnValue. And this return value is assigned to a variable in parent web form. Thereafter, it assigned to textbox.

The whole idea is that, window.returnValue returns some value from child window to parent window, and thereafter, you can do any thing with that returned value. You can even pass to VB code using parameters of query string of action attribute of document object.

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

So, from the last example we learnt a new 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, simply pop an alert message to user.

If you want to display some variable message in alert message then it you can do that with this slight modification.

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 will be a drawback again here, using above method to pop alert box, you will notice that if you try to run above code. We will talk about it later on.

Same thing can be done by registering JavaScript code to the browser. Following example will do the same thing, but here we are registering the JavaScript to 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 notice that drawback? Yes, you are right, it will keep screen of parent window blank till it opens that alert message or dialog box. All of the controls of parent window will remain unrendered on browser unless you will not close that alert box or dialog box.

Why?? This is because JavaScript which is generated is placed at the top of html page. You can easily understand this if you see that generated html code of the page. Look at the following:

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>

Or the 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 case, code is generated just below the form tag, but still it’s placed above all of the html and web controls. And when alert message or any modal dialog box is opened, control will gone to that opened dialog box and rest of the controls will not visible as they are not rendered yet. And when user close that alert message or modal dialog box, the rest of the controls rendered thereafter.

So, what actually I wanted to do is that it should open modal dialog box with all rendered controls in parent forms. It’s possible if you can place your generated JavaScript below the controls tags in the form. Here is the technique for that. Just use RegisterStartupScript method to place that JavaScript in web page. Look at the following code which will display an alert message and a modal dialog box. If you look at the generated html code you will easily understood the whole working flow behind this. Here is the generated html code.

<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 element and below all of the html or web controls tags. First all html controls will render on browser and thereafter modal dialog box or modal dialog box will open.

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

written by Firoz Ansari
The author didn‘t add any Information to his profile yet.

13 Responses to “Implementing dialog box in ASP.NET based web application”

  1. Firoz Ansari » Blog Archive » How to pass multiple values from child widow? says:

    [...] Firoz Ansari <blog /> « Implementing dialog box in ASP.NET based web application [...]

  2. Firoz Ansari » Blog Archive » Adding client script to server control in ASP.NET 2.0 says:

    [...] Sometime back I written an article on displaying dialog box in ASP.NET 1.1. As I have explained in that article, to pop a dialog box you need to add an attribute to the server control for event “onclick”. This requires server-side coding even if you want to display simple confirmation message. [...]

  3. Girish Kumar Sharma says:

    Then what is the use of system.windows.forms.messagebox.show (“This is message box”)? How it can be used? Why it has incorporated in .NET framework?
    Please guide me in that sense also.
    Thanks and regards
    Girish,Ajmer,Rajasthan (India)

  4. Firoz Ansari says:

    Hi Girish,
    You can not use system.windows.forms.messagebox.show method to pop up dialog box in ASP.NET based application. As you can see the namespace of method messagebox, it in windows forms, so it’s useful only if you are developing window based application. messagebox.show is only incorporated in window forms and NOT in ASP.NET

    To understand the actually problem associate with messagebox.show, create a simply web page and implement this method in any web based application. Now call URL of this web application from other machine. You will notice a very strange thing. And that’s the problem with using messagebox in web based application.

    Though, there are some third party libraries available which are implemented same like window form, but ultimately they are rendering some kind of javascript at browser to open dialog box.

  5. ELIZABETH says:

    hi, your code is very useful for me but one thing i have doubt on this.how can we pass the value from the child.aspx to the datagrid in parent.aspx.Please guide me in this

    thanks
    elizabeth

  6. Firoz Ansari says:

    Hi,
    You might have to trap ItemDataBound event of the datagrid where you can place javascript code which will open the dialog box. Add a template column in the DataGrid, and drop HyperLink on it. Now in ItemDataBound event, bind its onclick clientside event with javascript code to open the dialog box.
    Here is the example:

    private void dataGridCustomer_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
    if ((e.Item.ItemType == ListItemType.Item) | (e.Item.ItemType == ListItemType.AlternatingItem))
    {
    int customerId = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "CustomerID"));;
    string tempStr;
    HyperLink linkOpen = (HyperLink) e.Item.FindControl("linkOpen");

    linkOpen.Attributes.Add("onclick", "var strReturn; strReturn=window.showModalDialog('customer.aspx?id='" + customerId.ToString() + ",null,'status:no;dialogWidth:370px; dialogHeight:220px;dialogHide:true;help:no;scroll:no');");

    }
    }

    Note, how I am pulling customer id every time in code and passing it to JavaScript code.

    I am sure this will gives some pointers.

    Regards,
    Firoz Ansari

  7. Enrico says:

    I thank you for your note!!! It’s very useful.

  8. Jebat says:

    I’ve see & try from your source code, but in my pc, the source code can’t
    run if you click the button only 1 time. you must click 2 time. i’ve follow all from your source code. and the 2nd, about Msgbox(Message dialog). how the change button OK and Cancel to became Yes and No. thanks for your article and your information.

    Jebat

  9. Inds says:

    In the parent:

    CODE
    parentVar = “set by parent”;
    vRv = window.showModalDialog(“modalWindow.html”,window.self, “”);

    In the modal: How do we get the value from parent!!!!!!!!!!!!!!

    CODE [is not working]
    sVal = dialogArguments.parentVar
    alert(dialogArguments.parentVar);

  10. JKusmanto says:

    Your code is veryinterestiing for me.
    I have an idea for my Web-application, but I don’t know how to implement your code on it.
    My idea is (for example) 1 parent form with 2 children :
    In parent form, there are several textboxs one of the textboxs (let’s say) is Author_ID.
    When a user RIGHT CLICK on the textbox, a small dialog form (child 1) will appear with a message and 2 buttoms : “Do you want to add a new ID?” Ok and Cancel.
    If a user click on Yes, the form (child 1) will be closed and another form (child 2) will be shown to add a new ID. If the new code is already added, then return to the parent form.

    I believe we can do this kind of thing, but how to do?

    Regards,
    JK

  11. sindia says:

    If i use RegisterStartUpScript instead of RegisterClientscriptBlock, will the blank parent screen disappears?

  12. ashishtandel says:

    when we open any webpage a dialog using java script..in a title bar of dialog it shows
    “webpage dialog”. How can we remove this?

  13. Firoz Ansari says:

    @ashishtandel
    No. You can’t remove “Web Page Dialog” from the title. You can provide multiple “ ” in page title as work around but that will lead to having “…” at end of the title in dialog box.

Leave a Reply

Spam protection by WP Captcha-Free