Modal ASP.net user control - asp.net

I have a web form app where a couple of user-controls have been developed and placed on a page where a customer is building an order. The user-controls are pretty extensive in what they do, causing post-backs, etc.
I'd like to display them in a modal fashion without putting them in a separate page (if possible). So therein lies my question.
Is it possible to place user-controls within divs/panels, display them modally and keep them displayed modally (even through postbacks) until the user clicks a button on the control to dismiss it?
I'm basically looking at the modal option because I need to disable the rest of the form while the user is dealing with the sections the user-control is on. So I'm looking for a best-practice approach I suppose and some nudges in the right direction for this.
Thanks!
ADDITION:
I wanted to update this with the code I wrote in hopes that it might help somebody else and also if there is a better way to implement this, then I'm all ears too.
The basics of this is that I'm passing everything back and forth between my user control and the container page through session vars. I use this to tell the container page whether or not the user control is "finished" and until the flag is set to true, the container page just keeps re-displaying the user control modally on each postback. Seems to work well so far.
Markup:
<%# Register Src="../controls/mylabel.ascx" TagName="mylabel" TagPrefix="uc1" %>
<div style="width: 100%;">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to cart" OnClick="ButtonAddToCartClick" />
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlOutput" Visible="False" runat="server" Width="500px">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<div style="visibility: hidden;">
<asp:Button ID="ButtonHidden" runat="server" Text="Button" />
</div>
<asp:Panel ID="pnlDownload" Visible="False" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div style="width: 100%;">
<uc1:mylabel ID="mylabel1" runat="server" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
Code behind:
protected void Page_PreRender(object sender, EventArgs e)
{
InitializeControls();
}
protected void Page_Load(object sender, EventArgs e)
{
InitializeControls();
}
private void InitializeControls()
{
DisplayDownloadPanel(!SessionDownloadComplete);
if (SessionDownloadItemNumber != string.Empty)
{
Label1.Text = SessionDownloadItemNumber != "CANCEL" ? "Item ordered from control was: [" + SessionDownloadItemNumber + "]" : "Order was canceled.";
pnlOutput.Visible = true;
}
}
protected void ButtonAddToCartClick(object sender, EventArgs e)
{
bool haveWeSomeText = string.IsNullOrEmpty(TextBox1.Text) == false;
if (haveWeSomeText == true)
{
SessionDownloadComplete = false;
DisplayDownloadPanel(true);
}
}
private void DisplayDownloadPanel(bool show)
{
pnlDownload.Visible = show;
if (show == true)
{
ModalPopupExtender1.Show();
}
else
{
ModalPopupExtender1.Hide();
}
}
private string SessionDownloadItemNumber
{
get { return Session["DownloadItemNumber"] != null ? Session["DownloadItemNumber"].ToString() : string.Empty; }
}
private bool SessionDownloadComplete
{
get { return Session["DownloadComplete"] == null || Convert.ToBoolean(Session["DownloadComplete"]); }
set { Session["DownloadComplete"] = value; }
}

Have a look at ASP.NET Ajax Toolkit Modal popup extender

Take a look at the jQuery UI dialog.
It is a good solution for cross browser modal dialogs in the browser.
<script>
$(function() {
$( ".dialogClass" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
There are a few initial hiccups integrating it with asp.net. But all those are very well documented here on stackover flow itself.

Related

Why isn't my code-behind working properly?

Here's my code-behind file for a web form. I can't get certain arguments to work properly with my form.
protected void btn_Submit_Click(object sender, EventArgs e)
{//Enter arguments here...
}
protected void btn_Clear_Click(object sender, EventArgs e)
{
Response.Redirect("~/ContentRequest/BMC_PR_Event.aspx", true);
}
protected void ShowForm()
{
Open.Visible = true;
Success.Visible = false;
Failure.Visible = false;
}
protected void ShowSuccess()
{
Open.Visible = false;
Success.Visible = true;
Failure.Visible = false;
}
protected void ShowFailure()
{
Open.Visible = false;
Success.Visible = false;
Failure.Visible = true;
}
}
Here's the code I'm trying to get it to work with...
<asp:Button TabIndex="12" Text="Submit Request" ID="Button1" CssClass="submit" OnClientClick="return validateForm();" runat="server" onclick="btn_Submit_Click"></asp:Button>
<asp:Button TabIndex="13" Text="Clear Fields" ID="Button2" CssClass="clear" UseSubmitBehavior="false" runat="server" onclick="btn_Clear_Click"></asp:Button>
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</asp:Panel>
<asp:Panel ID="Success" Visible="false" runat="server">
<div class="message"><p>Your submission was sucessful.</p><p>An email receipt has been sent to the address provided with the details of this request.</p><p>Thank you.</p></div>
</asp:Panel>
<asp:Panel ID="Failure" Visible="false" runat="server">
<div class="message">
<p>There was an error with your request. If this persists, please report your trouble to _OHE Web Strategies.</p>
Not sure what else I can do here...
--Edit--
This is the error I get...
From the code you have pasted, i cannot see a Panel control with the ID 'Open'. Please do one of the following.
If you need another Panel for the 'open' functionality, add another asp:Panel with the is 'Open'
If you have removed the Open panel once you had, remove the code (from code behind in your case) related to that.
Best of luck
James

Cannot perform close/open ASP.Net Ajax ModalPopupExtenders in sequence from server side code

I'm having a problem hiding one ModalPopupExtender and Showing another within the same server-side call.
My app requires user input on some validating conditions. These conditions are evaluated in sequence and when certain conditions are true it requires a user to verify (click yes or no) via a ModalPopupExtender window. If the user clicks Yes, evaluation should continue and if another condition requires user input it should also open a modal dialog - until all conditions are passed.
I've got no problem if only one of the conditions requires input, but if more than one require input, only the first modal is displayed and I can't figure out why. When tracing the code it's clear that the Hide() on the first popup is hit and the Show() on the second popup is hit, but the second popup never shows up.
I've tried to pull out the relevant code blocks here with extreme simplification. It's a really complex project and I may have missed something but I hope it's enough to describe my problem.
Problematic process flow:
User clicks "Continue" -> DoContinue is called -> set conditions flags -> Show first modal popup -> Return to user
User clicks "Yes" -> calls condition 1 Yes click handler (set handled flag, hide modal popup) -> call DoContinue-> re-evaluate conditions flags -> attempt to show second modal popup -> return to user.
The first popup disappears but the second is never shown.
It's only a problem when Hide() is being called on the first modal in the same request where Show() is being called on the second.
MyContainerControl.ascx:
<%# Control Language="C#" AutoEventWireup="true" Inherits="MyContainerControl" %>
<input Type="Submit"
id="btnContinue"
Name="btnContinue"
Value="Continue"
OnServerClick="Continue_Click"
runat="server"/>
<asp:UpdatePanel
ID="updateCondition1"
runat="server"
ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<ajaxToolkit:ModalPopupExtender
ID="modalCondition1"
runat="server"
BehaviorID="dlgCondition1"
TargetControlID="btnFakeInvokeModalCondition1"
PopupControlID="divCondition1"
BackgroundCssClass="modalBackground"
DropShadow="true"
PopupDragHandleControlID="divDragCondition1"
RepositionMode="RepositionOnWindowResize"
CancelControlID="btnCondition1No" />
<input type="button"
id="btnFakeInvokeModalCondition1"
runat="server"
style="display: none" />
<div id="divCondition1"
runat="server"
class="modalPopup">
<custom:Condition1Control id="condition1" runat="server" visible="false" />
<div id="divDragCondition1"></div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel
ID="updateCondition2"
runat="server"
ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<ajaxToolkit:ModalPopupExtender
ID="modalCondition2"
runat="server"
BehaviorID="dlgCondition2"
TargetControlID="btnFakeInvokeModalCondition2"
PopupControlID="divCondition2"
BackgroundCssClass="modalBackground"
DropShadow="true"
PopupDragHandleControlID="divDragCondition2"
RepositionMode="RepositionOnWindowResize"
CancelControlID="btnCondition2No" />
<input type="button"
id="btnFakeInvokeModalCondition2"
runat="server"
style="display: none" />
<div id="divCondition2"
runat="server"
class="modalPopup">
<custom:Condition2Control id="condition2" runat="server" visible="false" />
<div id="divDragCondition2"></div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
MyContainerControl.cs:
public class MyContainerControl : System.Web.UI.UserControl
{
protected HtmlInputImage btnContinue;
//Condition1
protected AjaxControlToolkit.ModalPopupExtender modalCondition1;
protected UpdatePanel updateCondition1;
protected HtmlGenericControl divCondition1;
protected Condition1Control condition1;
//Condition2
protected AjaxControlToolkit.ModalPopupExtender modalCondition2;
protected UpdatePanel updateCondition2;
protected HtmlGenericControl divCondition2;
protected Condition2Control condition2;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
condition1.Condition1RaisedEvent += HandleCondition1Event;
condition2.Condition2RaisedEvent += HandleCondition2Event;
btnContinue.ServerClick += btnContinue_ServerClick;
}
protected void HandleCondition1Event(object sender, Condition1EventArgs e)
{
// use ship to store
ViewState["Condition1Yes"] = true;
ViewState["Condition1Value"] = e.Condition1Value;
modalCondition1.Hide();
DoContinue(sender);
}
protected void HandleCondition2Event(object sender, Condition2EventArgs e)
{
// use ship to store
ViewState["Condition2Yes"] = true;
ViewState["Condition2Value"] = e.Condition2Value;
modalCondition2.Hide();
DoContinue(sender);
}
protected void btnContinue_ServerClick(object sender, EventArgs e)
{
DoContinue(sender);
}
protected void DoContinue(object sender)
{
// test for conditions - just plug to true for demonstration
bool throwCondition1 !(ViewState["Condition1Yes"] == null ? false : (bool)ViewState["Condition1Yes"])
bool throwCondition2 = !(ViewState["Condition2Yes"] == null ? false : (bool)ViewState["Condition2Yes"])
// analyze conditions
if (throwCondition1)
{
var condition1Yes = ViewState["Condition1Yes"] == null ? false : (bool)ViewState["Condition1Yes"];
if (!condition1Yes)
{
divCondition1.Visible = true;
modalCondition1.Show();
return;
}
}
if (throwCondition2)
{
var condition2Yes = ViewState["Condition2Yes"] == null ? false : (bool)ViewState["Condition2Yes"];
if (!condition2Yes)
{
divCondition2.Visible = true;
modalCondition1.Show();
return;
}
}
// do other work
}
}
Condition1UI.ascx - Condition2UI.ascx is very similar:
<%# Control Language="C#" AutoEventWireup="true" Inherits="Condition1Control" %>
<div id="divCondition1Container" runat="server">
<input id="hdnCondition1Value" type="hidden" runat="server" value="<%# this.Condition1Value %>" />
<asp:Panel ID="pnlCondition1UI" runat="server">
<br />
<h2>
Warning!</h2>
<hr />
<br />
<div>
<p>Condition1 has been met.</p>
<br />
<br />
<p>Would you like to continue?</p>
</div>
<br />
<br />
</asp:Panel>
<div>
<table>
<tr>
<td align="center">
<asp:Button ID="btnCondition1Yes" runat="server" class="green" Text="Yes" style="padding: 3px 7px;" OnClick="DoCondition1YesClick" OnClientClick="$find('dlgCondition1').hide();" />
</td>
<td align="center">
<button id="btnCondition1No" class="red">No</button>
</td>
</tr>
</table>
<br />
</div>
<br />
</div>
Condition1Control.cs - Condition2Control.cs is almost identical:
public class Condition1EventArgs : EventArgs
{
public string Condition1Value { get; set; }
}
public class Condition1Control : System.Web.UI.UserControl
{
public HtmlInputHidden Condition1Value;
public event EventHandler<Condition1EventArgs> Condition1RaisedEvent;
protected virtual void RaiseCondition1Event(Condition1EventArgs e)
{
EventHandler<Condition1EventArgs> handler = Condition1RaisedEvent;
if (handler == null)
{
return;
}
handler(this, e);
}
public void DoCondition1ButtonYesClick(object sender, EventArgs e)
{
RaiseCondition1Event(new Condition1EventArgs{
Condition1Value = Condition1Value.Value
});
}
}
Change UpdatePanel's UpdateMode property to "Always" or don't forget to call 'Update' method of UpdatePanel which UI you want to update as result of postback fired from another UpdatePanel. So try to add updateCondition2.Update method call after modalCondition2.Show method in your code.

Webforms : Simplest way to allow a user to add/remove textboxes?

I don't want to use a gridview because the rest of the form isn't.
I simply need to be able to create a control to dynamically add/remove textboxes and get the value back either as a list of objects or a comma separated string.. It's proving to be much more difficult than it should.
I tried using Jquery + a regular asp.net textbox, but that only works nicely when they're starting from scratch--prepopulating the DOM with their information becomes a pain.
Is there something painfully simple that I'm missing?
It sounds like you could benefit from creating a CompositeControl.
I recently answered a similar question based on dynamically creating textboxes in which I provided a fairly detailed example.
See: Dynamically add a new text box on button click
Hope this helps.
You can add/remove the input[type=text] elements with jquery, and then use Request.Form in your code behind to get the values by element name.
javascript:
var itemCount = 0;
$("#list .add").click(function(){
itemCount++;
$(this).append("<input type='text' name='item"+itemCount+"'/><button class='remove'>Remove</button>");
});
$("#list .remove").click(function(){
$(this).prev().remove();
});
code behind:
string value1 = Request.Form["item1"];
string value2 = Request.Form["item2"];
There are two ways. The following is made using pure WebForm capabilities. Never do it in the production. It uses too much viewstate and too much updatepanel
this is a code behind
public List<String> ValueContainer {
get {
return (List<String>)ViewState["ValueContainer"];
}
set {
ViewState["ValueContainer"] = value;
}
}
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
ValueContainer = new List<string>();
}
}
private void PopulateRepeater() {
rp1.DataSource = ValueContainer;
rp1.DataBind();
}
protected void lbAdd_Click(object sender, EventArgs e) {
ValueContainer.Add("");
rp1.DataSource = ValueContainer;
rp1.DataBind();
}
protected void rp1_ItemCommand(Object Sender, RepeaterCommandEventArgs e) {
ValueContainer.RemoveAt(e.Item.ItemIndex);
rp1.DataSource = ValueContainer;
rp1.DataBind();
}
Here is the markup
<asp:ScriptManager runat="server" ID="sm1" />
<asp:UpdatePanel runat="server" ID="up1">
<ContentTemplate>
<asp:Repeater runat="server" OnItemCommand="rp1_ItemCommand" ID="rp1">
<ItemTemplate>
<asp:TextBox runat="server" ID="myTextBox" /> <asp:LinkButton Text="Remove" runat="server" ID="lbRemove" />
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton runat="server" ID="lbAdd" onclick="lbAdd_Click" Text="Add" />
</ContentTemplate>
</asp:UpdatePanel>
This is more lightweight version
<asp:HiddenField runat="server" ID="hfMyField" ClientIDMode="Static" />
<script type="text/javascript">
//<![CDATA[
function addTextBox() {
$("#myTextboxesContainer").append($("<input type='text' />").keyup(function () {
var Data = "";
$("#myTextboxesContainer input").each(function () {
Data += $(this).val() + ",";
});
$("#hfMyField").val(Data);
}));
}
//]]>
</script>
<div id="myTextboxesContainer">
</div>
Add textbox
The idea here is doing all dom manipulations using client script and storing everything in a hidden field. When the data is posted back you can retrive the value of the hidden field in a standard way i.e. hfMyField.Value. In this example it is CSV.

How to display value in the SimpleModal's dialog?

my question is really simple. I have a asp.net button. I can use it to call the simpleModal and have a dialog displayed. Now, I added a label control in the dialog, and would like this label to display some value. What should I do?
Here is my codes
$('#<%= btnOpen.ClientID %>').click(function(e) {
e.preventDefault();
$('#content').modal({
onOpen: function(dialog) {
dialog.overlay.fadeIn('slow', function() {
dialog.data.hide();
dialog.container.fadeIn('slow', function() {
dialog.data.slideDown('slow');
});
});
},
onClose: function(dialog) {
dialog.data.fadeOut('slow', function() {
dialog.container.slideUp('slow', function() {
dialog.overlay.fadeOut('slow', function() {
$.modal.close(); // must call this!
});
});
});
}
});
e.preventDefault();
// return false;
});
<asp:Button ID="btnOpen" runat="server" Text="ASP.NET Open"/>
<div id="content" style="display: none;">
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
I assume since you said that your question is simple that you just have an unfamiliarity with jQuery. You can put this in your click function, or in the $(document).ready function, depending on your full requirements:
var yourValue = ; // put your function or value here
$('#Label1').text(yourValue);
Note: You'll need to use .html instead of .text if you have a string with tags, but .text is faster.
Lol, I am answering my own question again, but I will give credit to mNVhr tho.
I finally get the whole thing work. The trick for asp.net button to fire a postback, along with javascript's postback, is to put the asp.net button into an update panel. Here is the code I have
For the javascript part:
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery.simplemodal-1.3.5.js" type="text/javascript"></script>
<script type="text/javascript">
function myOpen() {
$('#content').modal({
onOpen: function(dialog) {
dialog.overlay.fadeIn('slow', function() {
dialog.data.hide();
dialog.container.fadeIn('slow', function() {
dialog.data.slideDown('slow');
});
});
},
onClose: function(dialog) {
dialog.data.fadeOut('slow', function() {
dialog.container.slideUp('slow', function() {
dialog.overlay.fadeOut('slow', function() {
$.modal.close();
});
});
});
}
});
}
function myClose() {
$.modal.close();
}
</script>
For the HTML markup
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnOpen" runat="server" Text="Open" OnClick="btnOpen_Click" OnClientClick="myOpen();" />
</ContentTemplate>
</asp:UpdatePanel>
<div id='content' style="display: none">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<input id="Button2" type="button" value="Close" onclick="myClose();" />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
For the code behind:
protected void Page_Load(object sender, EventArgs e)
{
}
private void CloseDialog()
{
string script = string.Format(#"myClose()");
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "1")
CloseDialog();
else
Label2.Text = TextBox1.Text;
}
protected void btnOpen_Click(object sender, EventArgs e)
{
TextBox1.Text = DateTime.Now.ToString();
UpdatePanel1.Update();
}
I hope this tiny code can help those asp.net developer who want to use the nice jQuery in their projects.
As you can see, from the above codes.
When I click on the btnOpen button, two postbacks fired. One is from the asp.net code behind, which assign current datetime to the textbox control inside the modal dialog. The second postback is from the javascript, which open the modal dialog. The asp.net button has to be inside the update panel. Otherwise, the modal dialog will only stay for about 0.5 second.
When I click on the btnSave inside the modal dialog. Postback also occurred. I have a little logic here. When the textbox's value is 1, I call the closeDialog() function. When the value is other numbers, the modal dialog stay opening, and the label control inside the dialog will display the number from the text box.
jQuery is nice, but as a .Net developer, it is just new, and sometimes difficult for me to understand it, especially for the conflict of postbacks between javascript and .net.
I hope this answer is helpful.

JQuery DIalog and ASP.NET Repeater

I have an ASP.NET repeater that shows a list of items with a delete LinkButton.
I want to setup the Delete LinkButtons to show a JQuery Dialog for a confirmation. If the "OK" button is clicked, I want to do the postback.
The obvious problem is that each LinkButton in the repeater will have it's own ID and I don't want to have to duplicate all the javascript for the dialog.
Suggestions ?
The solution is not so simple. You must have the ability to call the original callback function after pressing the Ok button of jQuery UI Dialog.
First you need a generalized js function for showing the dialog:
function showConfirmRequest(callBackFunction, title, content)
{
$("#divConfirm").html(content).dialog({
autoOpen: true,
modal: true,
title: title,
draggable: true,
resizable: false,
close: function(event, ui) { $(this).dialog("destroy"); },
buttons: {
'Ok': function() { callBackFunction(); },
'Cancel': function() {
$(this).dialog("destroy");
}
},
overlay: {
opacity: 0.45,
background: "black"
}
});
}
I supposed the presence of a div like
<div id="divConfirm"></div>
On c# code-behind you have to register the previous client function, passing the original asp.net callbackFunction of your control as parameter (I generalized):
protected void AddConfirmRequest(WebControl control, string title, string message)
{
string postBackReference = Page.ClientScript.GetPostBackEventReference(control, String.Empty);
string function = String.Format("javascript:showConfirmRequest(function() {{ {0} }}, '{1}', '{2}'); return false;",
postBackReference,
title,
message);
control.Attributes.Add("onclick", function);
}
Through the method GetPostBackEventReference you have the ability to retrieve the postback function that asp.net assign to the control.
Now, on Repeater ItemDataBound, retrieve the control that execute the delete and pass it to this function:
<asp:Repeater ID="repeater" runat="server" OnItemDataBound="repeater_OnItemDataBound">
...
<ItemTemplate>
...
<asp:Button ID="btnDelete" runat="server" Text="Delete" />
...
</ItemTemplate>
</asp:Repeater>
and the code:
protected void repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
WebControl btnDelete = ((WebControl)e.Item.FindControl("btnDelete"));
AddConfirmRequest(btnDelete, "Confirm delete", "Are you sure? Really???");
}
}
I hope this helps.
<asp:GridView ... CssClass="mygridview"></asp:GridView>
and
$('table.mygridview td a').whatever()
That will allow you to work with all the link buttons simultaneously.
You can make it like this:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
...
<asp:LinkButton OnClick="DoSomething" OnClientClick="return ConfirmDelete();" ID="btnConfirm" runat="server" CssClass="button" Text="Delete"></asp:LinkButton><br /><br />
</ItemTemplate>
</asp:Repeater>
<script>
function ConfirmDelete() {
return confirm("Delete this record?");
}
</script>
or i think you could also make it like this:
<script>
$(function() {
$(".button").click(function() {
return confirm("Delete this record?");
});
});
</script>
in the ConfirmDelete Method, you can define your jQuery Confirm dialog
The question is definitely answered by tanathos, but I have another option working that avoids scripting in the code-behind if you are so inclined. I just hid the asp delete button using display:none and added a delete button that invokes the confirmation dialog and clicks the hidden asp delete button if the delete is confirmed.
The HTML in the repeater:
<ItemTemplate>
...
<td>
Delete
<asp:Button ID="DeletePolicyButton" runat="server" OnCommand="OnDeleteCommand" CommandArgument="Argument" Text="Delete" CssClass="delete-button" />
</td>
...
</ItemTemplate>
The CSS:
.delete-button
{
display: none;
}
The javascript:
// make the dummy button look like a button
$("a.dummy-delete-button").button({
icons: {
primary: "ui-icon-trash"
}
});
// create the dialog
var deleteDialog = $('<div>Are you sure you want to remove this policy?</div>')
.dialog({
autoOpen: false,
modal: true,
title: 'Delete Policy'
});
// handle click event to dummy button
$("a.dummy-delete-button").click(function (e) {
// don't follow the href of the dummy button
e.preventDefault();
// get a reference to the real ASP delete button
var button = $(this).closest('td').find('.dummy-delete-button');
deleteDialog.dialog({
buttons: {
// handle delete. Note: have to defer actual button click until after close
// because we can't click the button while the modal dialog is open.
"Delete": function () { deleteDialog.bind("dialogclose", function () { button.click() }); $(this).dialog("close"); },
// handle close
"Cancel": function () { $(this).dialog("close"); }
}
});
deleteDialog.dialog("open");
});
Hy,
First you should use Jquery Dialog or other clienside dialogs, it's more cooler.
You should have an html element on the page to invoke the Jquery dialog popup.
<div class="Popup"></div>
<script>
var confirm = false;
function ConfirmDelete(doPostback) {
$(".Popup").dialog(){ /* threat the dialog result , set confirm variable */ };
if(confirm) {
__doPostback(); }
else return false;
}
</script>
On the part where i put the comented sentence you can put code to handle the dialog result.
You could find info from the link above.
The function is returning false and because of that it blocks the execution of the server side code (the async postback).
The Button should look like:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton OnClientClick="ConirmDelete(<#%GetPostbackReference()%>)" CommandArgument = "<%# DataBinder.Eval(Container.DataItem, "Id") %>" OnClick="btnConfirm_Click" ID="btnConfirm" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
On the CommandArgument property i set the id of the item wich are binded to the repeater.
In this way on the btnConfirm_Click event you have acces to this paramater
void btnConfirm_Click(object sender, CommandEventArgs e)
{
e.CommandArgument -> you will find the id an you can execute the delete
}
You should have on the code behind:
protected string GetPostbackReference()
{
return Page.ClientScript.GetPostBackEventReference(btnConfirm, null);
}
This function is invoked on the binding of the element and returning the current controls postback method wich will look like __doPostback(source, param)
This is a javascript method wich you could excute easilly,and you have full control of the postbacks.
On clientside you can decide whether or not to call this postback event.
PS: If something is unclear post here a question and i will update the answer.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
...
<asp:LinkButton OnClick="DoSomething" OnClientClick="return ConfirmDelete();" ID="btnConfirm" runat="server" CssClass="button" Text="Delete"></asp:LinkButton><br /><br />
</ItemTemplate>
</asp:Repeater>
<script>
function ConfirmDelete() {
return confirm("Delete this record?");
}
</script>

Resources