Replace javascript confirm dialog box with jquery confirm dialog - c#

I am trying to write simple jquery confirm dialog with two buttons: delete and cancel. When dialog was written with javascript, everything worked well. Now cancel button works but delete button does not delete anything and just cancels deletion. I want commandname to call cmddelete property which will delete row.
I am using this example: http://www.codeproject.com/Tips/616118/jQuery-confirmation-in-ASP-NET-GridView
Csharp code:
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowIndex;
switch (e.CommandName)
{
case "CmdDelete":
rowIndex = (((LinkButton)e.CommandSource).Parent.Parent as GridViewRow).RowIndex;
DeleteItem(ViewData.List[rowIndex].ID);
Gridview:
<asp:LinkButton ID="btnDelete" runat="server" CommandName="CmdDelete"
Text="delete" OnClientClick="javascript:return deleteItem(this.name);" ></asp:LinkButton>
Javascript code:
function deleteItem(CmdDelete)) {
var dialogTitle = 'Message from the webpage';
$("#deleteConfirmationDialog").html('<p><span class="ui-icon " +
"ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>" +
"Please click delete to confirm deletion.</p>');
$("#deleteConfirmationDialog").dialog({
title: dialogTitle,
buttons: {
"Delete": function () { __doPostBack(CmdDelete, '');
$(this).dialog("close"); },
"Cancel": function () { $(this).dialog("close"); }
}
});
$('#deleteConfirmationDialog').dialog('open');
return false;
}

Related

Postback in jQuery UI dialog

I've a gridview with some rows.
On each row I have an imagebutton on the right side of the grid that offer the possibility to delete a record.
Clicking on the imagebutton is show a dialog created with jQuery UI.
jQuery code is:
$("[name*='btn_check']").click(function() {
event.preventDefault();
$("#dialog-confirm").dialog({
autoOpen: true,
resizable: false,
height: 200,
modal: true,
buttons: {
"Accept": function() {
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
});
Code is quite simple and common for jQuery UI dialog.
So, now I wan to execute code when "Accept" button is clicked and I though __doPostBack could be a good solution.
So, I've created an hidden button in my gridview (near the imagebutton), then I've added this code to "Accept" function, as I found on another StackOverflow question:
__doPostBack('btn_hidden', '');
I've also tried to use this:
__doPostBack('<%= btn_hidden.UniqueID %>', '');
But without success.
So, which is the right way to execute a postback and how can I send the ID of the record to delete this record with code behind?
First of all you should have a correct CommandName and CommandArgument set on your ImageButton. Then call dialog from the OnClientClick. As I understood you have only one dialog element hidden somewhere so there should be no problems with ids:
<asp:ImageButton runat="server"
CommandName="Delete"
CommandArgument='<%# Eval("YourKeyFieldNameHere") %>'
OnCommand="ImageButton_Command"
OnClientClick="javascript:return showConfirmDialog(this.name)"
/>
function showConfirmDialog(uniqueId) {
$("#dialog-confirm").dialog({
autoOpen: true,
resizable: false,
height: 200,
modal: true,
buttons: {
"Accept": function() {
$(this).dialog("close");
__doPostBack(uniqueId, '');
},
Cancel: function() {
$(this).dialog("close");
}
}
});
return false; // this is to prevent default click handler to cause a postback
}
Codebehind:
protected void ImageButton_Command(object sender, CommandEventArgs e)
{
// e.CommandArgument will contain the record key and
// e.CommandName will be equal to "Delete" or whatever you'll set on aspx
}

Why is LinkButton not executing the Click function from code behind

I have a GridView which has these two controls:
<asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' OnClick="btnShow_Click" />
<asp:LinkButton runat="server" ID="btnShow2" CssClass="btnSearch2" Text="View Allst" CommandName="ViewAll" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' PostBackUrl="JavaScript:void(0);" OnClientClick="return false;" OnClick="btnShow_Click">View Alls</asp:LinkButton>
code-behind:
protected void btnShow_Click(object sender, EventArgs e)
{
System.Web.UI.WebControls.Button btn1 = (System.Web.UI.WebControls.Button)(sender);
string strCA = btn1.CommandArgument;
string strCN = btn1.CommandName;
int index = 0;
if (strCN == "ViewAll")
{
index = Convert.ToInt32(strCA);
DataTable cacheTable = HttpContext.Current.Cache["ResultsTable"] as DataTable;
string column = cacheTable.Rows[index].Field<string>("Guideline");
string test = BookingResults.Rows[index].Cells[7].Text;
string html = HttpUtility.HtmlDecode(column);
ResultsDiv.InnerHtml = html;
}
}
JQuery:
$(document).ready(function () {
//Click the button event!
$(".btnSearch").click(function (e) {
e.preventDefault();
alert($(this).val() + " Clicked");
//centering with css
centerPopup();
//load popup
loadPopup();
});
$(".btnSearch2").click(function (e) {
e.preventDefault();
alert($(this).val() + " Clicked");
//centering with css
centerPopup();
//load popup
loadPopup();
});
$("#popupContactClose").click(function () {
disablePopup();
});
$("#backgroundPopup").click(function () {
disablePopup();
});
//Press Escape event!
$(document).keypress(function (e) {
if (e.keyCode == 27 && popupStatus == 1) {
disablePopup();
}
});
});
var popupStatus = 0;
//loading popup with jQuery magic!
function loadPopup() {
//loads popup only if it is disabled
if (popupStatus == 0) {
$("#backgroundPopup").css({
"opacity": "0.7"
});
$("#backgroundPopup").fadeIn("slow");
$("#popupContact").fadeIn("slow");
popupStatus = 1;
}
alert(popupStatus);
}
//disabling popup with jQuery magic!
function disablePopup() {
//disables popup only if it is enabled
if (popupStatus == 1) {
$("#backgroundPopup").fadeOut("slow");
$("#popupContact").fadeOut("slow");
popupStatus = 0;
}
alert(popupStatus);
}
//centering popup
function centerPopup() {
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#popupContact").height();
var popupWidth = $("#popupContact").width();
//centering
$("#popupContact").css({
"position": "absolute",
"top": windowHeight / 2 - popupHeight / 2,
"left": windowWidth / 2 - popupWidth / 2
});
//only need force for IE6
$("#backgroundPopup").css({
"height": windowHeight
});
}
HTML that displays the popup:
<div id="popupContact">
<a id="popupContactClose" title="Close Window">x</a>
<h3>Booking Guidelines</h3>
<asp:Panel ID="Panel1" runat="server" style="vertical-align:top" ScrollBars="Vertical" Height="300px" ForeColor="Black">
<div id="ResultsDiv" runat="server" style="vertical-align:top" > </div>
</asp:Panel>
</div>
<div id="backgroundPopup"></div>
The GridView generates multiple rows, where each row the button will have a different INDEX number to reference the session table being used to populate ResultsDiv.InnerHtml = html;.
When I click on btnShow Button it displays the alert and shows the popup with the updated ResultsDiv.InnerHtml = html; by using the code-behind for a split second and does a postback and reloads the page.
When I click 'btnShow2' LinkButton it displays the alert and shows the popup and does not do a postback. The only issue I am having is, it doesn't access the code-behind to update ResultsDiv.InnerHtml = html; so it is always displaying the same result no matter what row the button is clicked.
How do I modify my code so that it updates the ResultsDiv.InnerHtml = html; and displays the popup every time the button is clicked on any of the row and does NOT do a postback?
If You Remove Both
OnClientClick="return false;" and
PostBackUrl="JavaScript:void(0);" then definitely it will postback.
You can observe your HTML generated/rendered if you set both attributes with Postback event
WebForm_DoPostBackWithOptions which should be something like
javascript:__doPostBack('BookingResults$ctl02$btnShow2','')
View Alls
You have OnClientClick="return false;". That cancels the postback. To fix it, remove that attribute from your LinkButton declaration.
Also, not sure what PostBackUrl="JavaScript:void(0);" does. I've never seen someone to do that. You might try eliminating that if it's not necessary.

How to use a button to populate data without doing a postback

I have the following ASP.net button inside my GridView:
<asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnCommand="btnShow_Command" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' />
The code-behind is:
protected void btnShow_Command(object sender, CommandEventArgs e)
{
int index = 0;
if (e.CommandName == "ViewAll")
{
index = Convert.ToInt32(e.CommandArgument);
DataTable cacheTable = HttpContext.Current.Cache["ResultsTable"] as DataTable;
string column = cacheTable.Rows[index].Field<string>("Guideline");
string test = BookingResults.Rows[index].Cells[7].Text;
string html = HttpUtility.HtmlDecode(column);
ResultsDiv.InnerHtml = html;
}
}
The ResultsDiv is shown in a popup using the JQuery:
//CONTROLLING EVENTS IN jQuery
$(document).ready(function () {
//Click the button event!
$(".btnSearch").click(function (e) {
alert($(this).val() + " Clicked");
e.preventDefault();
//centering with css
centerPopup();
//load popup
loadPopup();
});
});
When I navigate to the page, the generated HTML looks as follow (there are multiple rows with the same button in the column):
<input type="button" name="ctl00$ctl33$g_36ed1b14_1f08_43fb_8099_eb3423a33ed9$BookingResults$ctl224$btnShow" value="View All" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl33$g_36ed1b14_1f08_43fb_8099_eb3423a33ed9$BookingResults$ctl224$btnShow", "", true, "", "", false, true))" id="ctl00_ctl33_g_36ed1b14_1f08_43fb_8099_eb3423a33ed9_BookingResults_ctl224_btnShow" class="btnSearch" />
What is happening now, is when I click the View All button it displays the alert, when I click OK, it displays the popup for a split second and refreshes the page.
How can I modify the code-behind/JQuery so that I can click on any of the button, and it will display the alert and show the popup every time and not do a postback?
I think the first thing you need to do even before alert is e.preventDefault();
//CONTROLLING EVENTS IN jQuery
$(document).ready(function () {
//Click the button event!
$(".btnSearch").click(function (e) {
e.preventDefault();
e.stopproPagation();
alert($(this).val() + " Clicked");
//centering with css
centerPopup();
//load popup
loadPopup();
});
});
As what i think that the alert lets the event do its default job first.

Call jquery modal popup from asp.net dropdownlist change

I have a requirement to do some logic execution upon change of dropdownlist value. Before executing the logic i need to take user confirmation and then call service side method to complete the process. Not sure How to call server side method based on modal popup confirmation response from user. So if user confirms with Yes button on the modal popup server side code should be called otherwise do nothing.
Here is the code i have . Server side does not get called upon modal popup confirmation.
function PopupDialog(title, text) {
var div = $('<div>').html('<br>'+text).dialog({
title: title,
modal: true,
height: 190,
width: 320,
buttons: {
"Yes": function () {
$(this).dialog('close');
},
"No": function () {
$(this).dialog('close');
}
}
});
return true;
};
<asp:GridView runat="server" ID="grdTransactions" SkinID="gridviewskin"
AllowSorting="true" AllowPaging="true" PageSize="30" Width="100%"
OnRowDataBound="grdTransactions_RowDataBound"
OnDataBound="grdTransactions_DataBound"
OnSelectedIndexChanged="grdTransactions_SelectedIndexChanged">
.............
<asp:TemplateField Visible="true" HeaderText="Status" >
<ItemTemplate>
<asp:Label runat="server" ID="lblStatus" Visible="False" Text='<%# ShowStatus( Container.DataItem ) %>' />
<asp:DropDownList ID="ddlTransactionList" AutoPostBack="True" OnSelectedIndexChanged="ddlTransactionList_SelectedIndexChanged" onchange="return PopupDialog('Remittance Confirmation','Are you sure you want to update the status?.');" runat="server"></asp:DropDownList>
<br/>
</ItemTemplate>
</asp:TemplateField>
**Server Side Code --**
protected void ddlTransactionList_SelectedIndexChanged(object sender,
EventArgs e)
{
//Your Code
if (OnDataChanged != null)
OnDataChanged(sender, e);
}
Thank you
I think there is a conflict between the javascript created by ASP.NET and the onchange event you are adding to the dropdown (onchange="return .... ") so it is ignoring the the call that posts back.
I would start by trying something like this on the front end:
// remove the autopostback & onchange from the ddl definition
<asp:DropDownList ID="ddlTransactionList" runat="server"></asp:DropDownList>
function PopupDialog(title, text) {
var div = $('<div>').html('<br>'+text).dialog({
title: title,
modal: true,
height: 190,
width: 320,
buttons: {
"Yes": function () {
$(this).dialog('close');
return true;
},
"No": function () {
$(this).dialog('close');
}
}
});
};
$(document).ready(function(){
$("<% ddlTransactionList.CLientID %>").change(function(){
if(PopupDialog('Remittance Confirmation','Are you sure you want to update the status?.')){
__doPostBack('ddlTransactionList')
}
});
});
In the code-behind:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"]; // parameter
// Request["__EVENTTARGET"]; // ddlTransactionList
// make your call to ddlTransactionList_SelectedIndexChanged() here
}
Let us know if this helps.

extjs/c# Yes saves to the database

I have a simple question.
I have a FormView, with a save button. When the button is clicked, it saves to databse.
I've added an EXT message box to confirm if user wants to save the data or not. when he click yes on the messagebox yes button, then it should save the data.
I can't find where to write the yes button logic in the ext.
Here is my code :
<asp:FormView ID="myform" runat="server" DataSourceID="mydatasource" DefaultMode="Edit" DataKeyNames="Id" >
<EditItemTemplate>
<asp:TextBox ID="myText" runat="server" TextMode="MultiLine" ClientIDMode="Static"
Text='<%#Bind("xx") %>' />
<ext:Button ID="btn_Update" runat="server" AutoPostBack="false" CausesValidation="false" CommandName="Update" Text="Speichern" StyleSpec="float: left; margin-left:10px;"> <DirectEvents>
<Click OnEvent="btnUpdateClick"></Click>
</DirectEvents>
</ext:Button>
<script type="text/javascript">
function showResult(btn)
{
Ext.example.msg('Button Click', 'You clicked the {0} button', btn);
};
function showResultText(btn, text)
{
Ext.example.msg('Button Click', 'You clicked the {0} button and entered the text "{1}".', btn, text);
}
var showResult = function (btn) {
Ext.Msg.notify("Button Click", "You clicked the " + btn + " button");
};
var showResultText = function (btn, text) {
Ext.Msg.notify("Button Click", "You clicked the " + btn + 'button and entered the text "' + text + '".');
};
</script>
protected void btnUpdateClick(object sender, DirectEventArgs e)
{
X.Msg.Confirm("Confirm", "Are you sure you want to save?", new JFunction { Fn = "showResult" }).Show();
}
I guess you are looking for this: (Can be placed in any Demo-Box of the Sencha API)
Edit 2
I have totally overseen that you are using Direct. You should mention such things.
Is there any reason for using DirectEvent? I couldn't test it but how about this (the wrapping function may be unnecessary, but a normal ExtJS handler get button reference as first argument):
<form runat="server">
<ext:ResourceManager runat="server" />
<script runat="server">
[DirectMethod]
public void SetTimeStamp(string field)
{
// do your saving
}
</script>
<ext:TextField ID="TextField" runat="server" FieldLabel="Label"/>
<ext:Button ID="Button" runat="server" Text="Click Me" Icon="Lightning">
<Listeners>
<Click Handler="function() {Ext.Msg.show({title: 'Save?', msg: 'Do you want to save the data?:', buttons: Ext.Msg.YESNO,fn: function(btn){ if(btn == 'yes') {App.direct.SetTimeStamp(#{TextField}.getValue());}}})}" />
</Listeners>
</ext:Button>
</form>
Edit 1 Simply use Ext.Ajax.request()
Ext.Msg.show({
title: 'Save?',
msg: 'Do you want to save the data?:',
buttons: Ext.Msg.YESNO,
fn: function(btn, text){
Ext.Ajax.request({
url: 'yourUrl',
method: 'POST',
params: {
// your params
},
success: function() {
console.log('success');
},
failure: function() {
console.log('woops');
}
});
}
});
Form example removed
Thank you all for your support, I found my way through your answers I will put it here maybe it can be useful for someone.
First, button code, need to have Isupload = "true"
ext:Button ID="btn_Update" runat="server" AutoPostBack="false" CausesValidation="false"
CommandName="Update" Text="Save" StyleSpec="float: left; margin-left: 10px;"
AutoScroll="False">
<DirectEvents>
<Click OnEvent="btnUpdateClick" IsUpload="true" AutoDataBind="true">
</Click>
</DirectEvents>
</ext:Button>
in the button event in the aspx :
protected void btnUpdateClick(object sender, DirectEventArgs e)
{
MessageBoxButtonConfig buttonYes = new MessageBoxButtonConfig();
buttonYes.Text = "Yes";
buttonYes.Handler = "Ext.net.DirectMethods.ClickedYES();";
MessageBoxButtonConfig buttonNo = new MessageBoxButtonConfig();
buttonNo.Text = "NO";
// buttonNo.Handler = "Ext.net.DirectMethods.ClickedNO();";
MessageBoxButtonsConfig yesNoButtons = new MessageBoxButtonsConfig();
yesNoButtons.Yes = buttonYes;
yesNoButtons.No = buttonNo;
X.Msg.Confirm("Save Changes", "Would you like to Save?", yesNoButtons).Show();
}
Last the Yes method that will save to database:
[DirectMethod]
public void ClickedYES()
{
Formview.UpdateItem(false);
Formview.DataBind();
}
I would suggest that instead of wiring the yes button of the dialog to perform the postback. You should wait for the message box to close and then invoke the postback functionality if the user clicked yes.
For example:
Ext.Msg.prompt('SaveChange', 'Would you like to save the changes?:', function(btn, text){
if (btn == 'yes'){
__doPostBack('btnSubmit','OnClick');
}
});
Replace btnSubmit with the name of your button.
Although the above solution would be my recommended approach, you could, alternatively, use jquery by doing:
$('btnSubmit').trigger('click');
Source: http://dev.sencha.com/playpen/docs/output/Ext.MessageBox.html

Categories