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
}
Related
I have an ASP.Net web application (with Master Page) and I've created a jQuery Dialog on one of the child pages. This dialog is used to display error messages to the operator if and when they happen in the code behind (e.g. saving error, etc.). So there isn't any one button or control that opens this dialog. For testing purposes only, I created an ASP button on the page to be sure I could open the dialog from the code behind. If the jQuery dialog is set with autoOpen:true, that ASP button will open the dialog every time. Obviously the dialog is open initially on page load, but if I close it, I can open it back up with that button. However, if I set autoOpen:false, that ASP button will not show/open the dialog. So I know for sure that my code behind for opening the dialog is correct since it works as stated previously. I've got the jQuery dialog code wrapped in a function that I reference in a "$(document).ready", but it still isn't working. Not sure what I am doing wrong. The div for the dialog is NOT contained in an UpdatePanel. I've seen many other posts about "similar" issues with showing the dialog when autoOpen:false, but some of them don't apply and others I've already tried or incorporated their suggestions.
$(document).ready(function ()
{
ShowPopup();
});
function ShowPopup(msgBoxTitle) {
$(function () {
$("#UserMessageBox").dialog(
{
autoOpen: false,
resizable: false,
height: "auto",
width: 600,
modal: true,
title: msgBoxTitle,
dialogClass: 'UserMessagBox',
buttons:
{
"Close": function () {
$(this).dialog("close");
},
"Next Message": function () {
var disableCloseBtn = ShowNextMessage();
if (disableCloseBtn) {
$(".ui-dialog-buttonpane button:contains('Close')").button("disable");
}
else {
$(".ui-dialog-buttonpane button:contains('Close')").button("enable");
}
},
},
open: function () {
$(".ui-dialog-buttonpane button:contains('Close')").button("disable");
},
});
});
};
When "autoOpen" is "false" the dialog will not open when you initialize it like you do on your function. you need to use the "open" method for this:
$("#UserMessageBox").dialog("open");
Documentation is here:
autoOpen
open
Update: exactly like the link you provide in the comment. and works.
you can actually call the open method where ever you want after you first initilized the dialog. so after you run ShowPopup, you can run "open" where ever you want on your app.
Update: i did some more changes like to match what you wrote.
So now you initilize the dialog and then call it on your script "ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Popup", "ShowPopup('" + message + "');", true);" just to update the data and title and open it. i put the first open on load just to show that when you close it you can run the ShowPopup any time (on my test it was with the button) like in your script.
$(document).ready(function ()
{
InitPopup();
//just for test
//ShowPopup('My Test Message');
//put this code where ever you want. like in the button i createed
//$("#UserMessageBox").dialog("open");
});
function InitPopup() {
//i removed the function you created here
$("#UserMessageBox").dialog(
{
autoOpen: false,
resizable: false,
height: "auto",
width: 600,
modal: true,
title: '',
dialogClass: 'UserMessagBox',
buttons:
{
"Close": function () {
$(this).dialog("close");
},
"Next Message": function () {
var disableCloseBtn = ShowNextMessage();
if (disableCloseBtn) {
$(".ui-dialog-buttonpane button:contains('Close')").button("disable");
}
else {
$(".ui-dialog-buttonpane button:contains('Close')").button("enable");
}
},
},
open: function () {
$(".ui-dialog-buttonpane button:contains('Close')").button("disable");
},
});
};
function ShowPopup(msgBoxTitle) {
$("#UserMessageBox").html('');
$("#UserMessageBox").append('<p>' + msgBoxTitle + '</p>');
$("#UserMessageBox").dialog("option", "title", msgBoxTitle);
$("#UserMessageBox").dialog("open");
}
$('#btn').on('click', function() { ShowPopup('New Message.'); })
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<div id = "UserMessageBox"></div>
<button id="btn">button</button>
Using #Yair solution, I modified it slightly to include what the OP did in the this post
Here is the final working script code:
<script type="text/javascript">
$(document).ready(function () {
InitPopup();
//just for test
//ShowPopup('My Test Message');
});
function InitPopup() {
$("#UserMessageBox").dialog(
{
autoOpen: false,
resizable: false,
height: "auto",
width: 600,
modal: true,
title: '',
dialogClass: 'UserMessagBox',
buttons:
{
"Close": function () {
$(this).dialog("close");
},
"Next Message": function () {
var disableCloseBtn = ShowNextMessage();
if (disableCloseBtn) {
$(".ui-dialog-buttonpane button:contains('Close')").button("disable");
}
else {
$(".ui-dialog-buttonpane button:contains('Close')").button("enable");
}
},
},
open: function () {
$(".ui-dialog-buttonpane button:contains('Close')").button("disable");
},
});
};
function ShowPopup(msgBoxTitle)
{
$(function ()
{
$("#UserMessageBox").dialog("option", "title", msgBoxTitle);
$("#UserMessageBox").dialog("open");
});
return false;
}
</script>
Here is the other markup (minus master page stuff):
<asp:Button ID="ShowPopupMsgTestBtn" runat="server" Text="Show Popup" OnClick="ShowPopupMsgTestBtn_Click" />
<asp:HiddenField ID="NextMessageIndexHF" runat="server" />
<asp:HiddenField ID="userMessagesHF" runat="server" ValidateRequestMode="Disabled"/>
<asp:HiddenField ID="UserDialogVisableHF" runat="server" />
<%--the following div makes up a dialog box used by the jQuery dialog--%>
<div id="UserMessageBox" title="User Message" style="display:none; ">
<div style="text-align: left; margin-bottom: 5px; border-bottom: 2px solid black; padding: 5px 5px 5px 10px">
<asp:Label ID="popupMsgHeaderLbl" runat="server" Text="Message" ForeColor="Black"></asp:Label>
</div>
<div style="text-align: left; padding: 10px; margin-bottom:40px">
<asp:Label ID="popupMsgLbl" runat="server" Text="Here is a message" ValidateRequestMode="Disabled"></asp:Label>
</div>
</div>
And here is the code behind for the ASP button control I was using only for testing purposed to show I could open the jQuery dialog box from code behind.
protected void ShowPopupMsgTestBtn_Click(object sender, EventArgs e)
{
string message = "Test Message";//not used right now but we may use this later as a parameter to "ShowPopup2()" below
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Popup", "ShowPopup('" + message + "');", true);
}
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;
}
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.
I have a issue with Jquery Modal dialog being called from a button inside an update panel..
here are the insights..
Javascript used for opening a Jquery modal dialog in aspx page..
<script type='text/javascript'>
function openModalDiv(divname) {
$('#' + divname).dialog({
autoOpen: false,
bgiframe: true,
closeOnEscape: true,
modal: true,
resizable: false,
height: 'auto',
buttons: { Ok: function () { closeModalDiv(divname) } },
open: function (event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); }
});
$('#' + divname).dialog('open');
('#' + divname).parent().appendTo($('form:FrmSearch'));
$('#' + divname).css('overflow', 'hidden')
}
function closeModalDiv(divname) {
$('#' + divname).dialog('close');
}
</script>
the button in aspx page..
<asp:UpdatePanel ID="upDialogs" runat="server">
<ContentTemplate>
<asp:Button ID="btnOpenDialog" runat="server" Text="Open Dialog" onclick="btnOpenDialog_Click" />
</ContentTemplate>
</asp:UpdatePanel>
The Div which needs to be called from code behind via javascript..
<div id="ErrorDiv2" title="Error" style="visibility:hidden">
<p><span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>Please select an option among the results and try again!</p>
</div>
Finally the code behind ..
protected void btnOpenDialog_Click(object sender, EventArgs e)
{
if (ProfileID == null)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorDivOpen", "document.getElementById('ErrorDiv2').style.visibility = 'visible';", true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorDivShow", "openModalDiv('ErrorDiv2');", true);
}
}
Now the Issue in detail..
Without the update panel the modal dialog pops very fine but makes full post back..
I want to have only a partial post back and hence am using a update panel..
The following are the solutions I have tried..
Added update panel to the existing div, dint work.
added an update panel along with runat="Server" for the div, still dint work..
Can any one help me with possible solutions?
Thanks for your quick reply but I found another solution.
I added both update panel and runat parameters to the Div.
<asp:UpdatePanel ID="upErrorDiv" runat="server"><ContentTemplate>
<div runat="server" id="ErrorDiv2" title="Error" style="visibility:hidden">
<p><span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>Please select an option among the results and try again!</p>
</div>
</ContentTemplate></asp:UpdatePanel>
Changed the code behind as.
if (ProfileID == null)
{
ScriptManager.RegisterStartupScript(ErrorDiv2,this.GetType(), "ErrorDivOpen", "document.getElementById('ErrorDiv2').style.visibility = 'visible';", true);
ScriptManager.RegisterStartupScript(ErrorDiv2,this.GetType(), "ErrorDivShow", "openModalDiv('ErrorDiv2');", true);
return;
}
Could you try injecting the javascript into a Literal control inside UpdatePanel, istead registering it with ClientScriptManager ?
Kris
I'm using Jquery dialogs in my Asp.net web application for all my messages.
Now I've tried to fill a listview with customers inside a dialog and its working, but I want to allow the user to use paging in the listview for choosing his customer out of the list.
When I press the button to move up 1 page, it ain't working...
Maybe it's just not possible? Or does someone have an example of paging a datacontrol in a Jquery dialog?
Greetz,
Ben
I suspect that the dialog is not being displayed after the paging postback?
You have two options:
One: Change to using a popup window with the listview so that the paging is handled in the normal way in its own page
Two: On the serverside, when rendering pages, also render a startup jQuery script that re-displays the dialog.
<div id="dialog" style="display:none;" >
<asp:listview ID="lv" runat="server" />
...etc
</div>
In code behind:
var script = new StringBuilder();
script.AppendLine("jQuery(function($) {");
script.AppendLine(string.Format(" $('#dialog').attr('Title','{0}');", dialogTitle));
script.AppendLine(" $('#dialog').dialog({ closeOnEscape: true, modal: true });");
script.AppendLine("});");
ClientScript.RegisterStartupScript(GetType(), "dialog", script.ToString(), true);
The 2nd option works!
I only added this code in codebehind:
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "openDialogScript", "$(function() { openCustomerDialog(); });", true);
And in the .aspx file I added this:
openCustomerDialog = function openDialog(){
$("#reportCustomerDialog").dialog({
modal: true,
height: 420,
width: 500,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
});
$("#dialog").show();
};