Thursday, March 22, 2012

Modal Dialog Form User Control

I've googled and found samples of Modal Dialog Form, but so far what I found is separate pieces carrying hard coded Javascript. It would be nice if there's one that works like an user control to be plugged into a form and return a Yes/No value. Thanks for any help.

Here's the code for a very simple user control that will prompt the user with a question and return a True/False value back on the server.

The .ascx code is

<%@.ControlLanguage="C#"AutoEventWireup="true"CodeFile="YesNo.ascx.cs"Inherits="YesNo" %>
<asp:ButtonID="Button1"runat="server"Text="Button"OnClientClick="javascript: return AskTheQuestion();"/>
<asp:HiddenFieldID="HiddenField1"runat="server"/>
The .ascx.cs codebehind code is:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

publicpartialclassYesNo : System.Web.UI.UserControl
{
privatestring _question ="";
privatebool _pbof =false;
protectedvoid Page_Load(object sender,EventArgs e)
{
string script ="function AskTheQuestion()" +
"{" +
"var result = confirm('" + _question +"'); " +
"document.getElementById(\"" + HiddenField1.ClientID +"\").value = result;" +
(_pbof ?"return true;" :"return result; ") +
"}\r\n";
this.Page.ClientScript.RegisterClientScriptBlock(typeof(YesNo ),"AskTheQuestion", script,true );
}
publicbool PostbackOnFalse
{
get {return _pbof; }
set { _pbof =value; }
}

publicstring ButtonText
{
get {return Button1.Text; }
set { Button1.Text =value; }
}

publicstring Question
{
get {return _question; }
set { _question =value; }
}
publicbool YesNoValue
{
get {return HiddenField1.Value =="true"; }
}
}
The way it works is as follows. The hidden field in the control is used to hold the true/false value from the confirm() on the client side. This is accessed (from a page) on the server code via the YesNoValue property. You use the Question property on the user control to set the question that you want to ask. You set the PostbackOnFalse property to True to have the button postback all the time, regarless of the option the user chooses on the modal dialog.
This control almost certainly won't do exactly what you want, but it should give you a clear idea of how to create a control that does.
And by the way, the control was written in VS 2005, but it's very easy to tweak it down to VS 2003 (ASP.NET 1.1).


That looks great! Could you pass me the code in VB2003? Thanks.

0 comments:

Post a Comment