Tuesday, November 20, 2007

ModalPopup Extender

I always think it's really nice for some web sites to popup a dialog, while the background color fades out. It's actually quite easy to make it happen with ASP.NET Ajax Control Extender now. ^_^

Copy these classes to your css file:

.modalBackground
{
background-color:Gray;
filter:alpha(opacity=70);
opacity:0.7;
}

.modalPopup
{
background-color:#FFFFDD;
border-width:3px;
border-style:solid;
border-color:Gray;
padding:3px;
width:250px;
}

During design time, add the following controls to the web page.



In the HTML page, add these attributes to the ModalPopupExtender:


<ajaxToolkit:ModalPopupExtender 
id="ModalPopupExtender2"
runat="server"
OnOkScript="fnClickOK()"
CancelControlID="btnCancel1"
OkControlID="btnOK1"
DropShadow="true"
BackgroundCssClass="modalBackground"
PopupControlID="Panel2"
TargetControlID="btnClickToOpen">

For the popup Panel, define these attributes:


<asp:Panel 
id="Panel2"
runat="server"
style="display: none"
CssClass="modalPopup">

Create this function in javascript, if you want to use the server-side postback, otherwise you can just create a javascript function where you will perform something when the user clicks on OK button in the popup dialog.


function fnClickOK(sender, e)
{
__doPostBack(sender,e);
}

 

Set the OnClientClick event for the "Click here!" button and "OK" button in the Page_Load event.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnOk1.OnClientClick = String.Format("fnClickOK('{0}','{1}')", btnOk1.UniqueID, "");
btnClickToOpen.OnClientClick = String.Format("fnClickOK('{0}','{1}')", btnClickToOpen.UniqueID, "");
}
}


 

Enter the codes in the btnOk1_Click & btnClickToOpen_Click event.

Call the ModalPopupExtender Show() method to popup the modal dialog.

protected void btnOk1_Click(object sender, EventArgs e)
{
lblName.Text = "Hello, " + txtName.Text +
". You have selected " + DropDownList1.Text;
}

protected void btnClickToOpen_Click(object sender, EventArgs e)
{
DropDownList1.Items.Clear();
DropDownList1.Items.Add("Red");
DropDownList1.Items.Add("Purple");
DropDownList1.Items.Add("Black");
ModalPopupExtender2.Show();
}

* If you want to refer to an external javascript file, you just need to add this line of code in the HTML file:


<script language="javascript" type="text/javascript" src="AjaxPrototype.js"></script>

2 comments:

  1. Is there a way to make the popuped up window apear when the page loads, without having to click on something to triger showing it ?

    ReplyDelete