JQuery DIalog and ASP.NET Repeater - asp.net

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>

Related

The value of checkbox is wrong in asp.net

I am using asp.net. I want to show unchecked checkbox but in the browser the status of the checkbox is true and I have set the checkbox.checked= false in serverside code but it displays checked in the browser.
Here is my code
{<asp:CheckBox ID="SendNotificationCheckBox" runat="server" Checked="false" Enabled="false" oncheckedchanged="SendNotificationCheckBox_CheckedChanged" AutoPostBack="true"/>}
I tried this piece of code in server side:
{ protected void SendNotificationCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (SendNotificationCheckBox.Checked == true)
{
NotificationPanel.Visible = true;
NotificationMessageTextBox.Text = "Business Listing Named:" + BusinessNameLabel.Text.Trim() + " Will Be Expired On" + NextVerificationDateLabel.Text.Trim() + ".Contact Us To Renew it.";
}
else if (SendNotificationCheckBox.Checked == false)
{
NotificationPanel.Visible = false;
}
}}
I know this isn't what you asked, but I think JavaScript / JQuery would be best for this kind of things. Place the following code in the head of your page
<script type="text/javascript">
function toggleVisibility(cb) {
var x = document.getElementById("NotificationPanel");
x.style.display = cb.checked ? "block" : "none";
}
</script>
and in your Checkbox
<asp:CheckBox ID="SendNotificationCheckBox" runat="server" Checked="false" onclick="toggleVisibility(this);"/>
<asp:Panel runat="server" ID="NotificationPanel" style="display: none;">
skjhaskjf
</asp:Panel>
or if You want to use JQuery, add this in your Head
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#SendNotificationCheckBox").click(function () {
$(this).is(':checked') ? $("#NotificationPanel").show() :
$("#NotificationPanel").hide();
});
});
</script>
and your checkbox
<asp:CheckBox ID="SendNotificationCheckBox" runat="server" Checked="false"/>
<asp:Panel runat="server" ID="NotificationPanel" style="display: none;">
skjhaskjf
</asp:Panel>
Here is the solution to your problem as you wanted.
You were unchecking the textbox and disabling it in PageLoad. If you do that, every time when the control comes to the server, PageLoad will be executed, and the checkbox will be be disabled. and after executing the pageload, the event 'SendNotificationCheckBox_CheckedChanged' will be executed.
Since the Checkbox is unchecked in the pageload, the code you have written if Checkbox is checked will be of no use. So, you have to check whether the page is loading for the first time. If so, Uncheck the checkbox or else don't.
You have to Do that by Checking for IsPostBack property by
If(!IsPostBack)
{
CheckBoxID.Checked=false;
CheckBoxID.Enabled=false;
}
If your checkbox is inside update panel,
then you need to update your update panel..

Checkboxlist in hidden DIV

I have a CheckboxList within a DIV. The DIV appears as a modal popup when a button is clicked. Then the user checks off any number of items in the checkboxlist and clicks OK. This hides the div.
once the user clicks the save button on the main form, I need to pass parameters to a stored procedure based on which items in the checkboxlist were clicked, but they are always set to unchecked when I run the save code. I'd love some thoughts on how to do this properly.
Thanks
JQuery:
$(document).ready(function () {
$('#<%=txtLANG.ClientID %>').click(function () {
$("#overlay-back").dialog({
resizable: false,
modal: true,
width: 500,
height: 400,
buttons: {
OK: function () {
GetLanguages();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
});
Save Method in CodeBehind
private void Save()
{
List<string> lstItemsChecked = new List<string>();
for (int i = 0; i < chkTopLanguages.Items.Count; i++)
{
if(chkTopLanguages.Items[i].Selected)
lstItemsChecked.Add(chkTopLanguages.Items[i].Value);
}
//stored proc call
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
Save();
}
ASPX Code for DIV popup and CheckBoxList
<div id="overlay-back" style="display:none;">
<td rowspan="3" valign="top">
<asp:CheckBoxList ID="chkTopLanguages" TextAlign="Right" runat="server" />
<br />
<asp:TextBox runat="server" ID="txtOtherLanguages" Text="Other Languages..."></asp:TextBox>
</td>
</div>
maybe this happens because the when you close the popup, the controls on the popup are not accessible. I don't know the exact cause but you can create an array variable in javascript. Whenever you check or uncheck a checkbox; with the help of javascript, you modify that variable to what all variables are set or not.
I used modal popup way long back and there was an issue like that only.
This approach might not be optimal but will work for sure.
Try setting the AutoPostBack to false:
<asp:CheckBoxList ID="chkTopLanguages" TextAlign="Right" runat="server" AutoPostBack="false" />
For the CheckBoxList control.

Modal ASP.net user control

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.

ASP.NET DataPager Next/Previous buttons client onlick event

How can I add client (javascript) onclick event to Next/Previous links in DataPager?
You Can add a new button in data pager and worked on it's click event.
<asp:ListView runat="server" ID="ListView1"
DataSourceID="SqlDataSource1">
<LayoutTemplate>
<table runat="server" id=" table1">
<tr runat="server" id="itemPlaceholder">
</tr>
</table>
<!-- This is the pager. Define all necessary markup here. -->
<asp:DataPager runat="server" ID="DataPager" PageSize="5">
<Fields>
<asp:TemplatePagerField>
<PagerTemplate>
<asp:Button ID="btn_Submit" runat="server" Text="Button" onclientclick="eventHandler(this)" />
</PagerTemplate>
</asp:TemplatePagerField>
</Fields>
</asp:DataPager>
</LayoutTemplate>
</asp:ListView>
The answer above (by Sheery) works great for custom pager elements. However, when using the stock Numeric or Next/Previous pager styles of the ListView or DataGrid, you don't have near as much control. By using client-side jQuery/javascript selectors, you can unobtrusively attach client-side handlers to the pager elements. For this example, I'm tracking if any form field value has changed and if so, then prior to allowing the pager to execute it's default behavior of posting back to the server, we're confirming with the user that they have unsaved changes.
$(function () {
var _formChanged = false;
// grabs all pager links in last row of table named dgQuestions
// and attachs a click eventhandler via jQuery library
$("#dgQuestions tr:last a").click(function(e) {
if (!_formChanged)
return true;
var ok = confirm('You have UNSAVED changes. Continue?');
if (ok) {
return true;
}
else {
//Prevent the submit event and remain on the screen
e.preventDefault();
return false;
}
});
// delegates change event handling to the form to indicate if ANY
// form field value changed for testing prior to paging
$("#form1").change(function(e) {
_formChanged = true;
});
});
});
OR
Can also utilize the beforeunload event of the window to catch ANY navigate-away action to test for unsaved changes as well. This code excludes the actual click of the 'save' button.
$(window).on('beforeunload', function (e) {
if (e.originalEvent.explicitOriginalTarget.id != "btnSave") {
if (_formChanged)
return 'You have UNSAVED changes. Continue?';
}

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.

Resources