Blog Archives

Jquery Modal dialog as Confirm in Asp.Net webforms

I love Jquery! it made me friends with client side scripting. Earlier it used to haunt me all the time.

If we have a button on a webform which should confirm the user action on click like a Delete button Jquery provides
Javascript methods:

<script type="text/javascript">
 $(document).ready(function () {
// this method opens a div with id="dialogContent" as a modal dialog box with Yes and No buttons.

$('#dialogContent').dialog({

autoOpen: false,
modal: true,
 bgiframe: true,
 title: "Confirm your action",
 width:200,
 height: 200
 });

});

// this method is called when Delete button is clicked.
function rowAction(uniqueName) {

$('#dialogContent').dialog('option', 'buttons',
 {
 "Yes": function () {
 __doPostBack(uniqueName, '');
 $(this).dialog("close");
 },
 "No": function () { $(this).dialog("close"); }
 });

$('#dialogContent').dialog('open');

return false;
 }
 </script>

.aspx code:


<asp:Button ID="btnDelete" runat="server" CommandArgument='<%# Eval("ProductID") %>'
Text="Edit" OnClick="btnDelete_Click" OnClientClick="javascript:return rowAction(this.name);" />

<div id="dialogContent">
Are you sure?

</div>

Code behind :


protected void Page_Load(object sender, EventArgs e)
 {

// register the postback reference. specify the control we are forcing to postback.

ClientScript.GetPostBackEventReference(btnDelete, string.Empty);
 }

// this event is fired when user presses <strong>Yes</strong> from Confirm Modal dialog.

protected void btnDelete_Click(object sender, EventArgs e)
 {
Button b = sender as Button;
if (b != null)
{
// do your actions here
}
 }

This way we get Jquery modal confirm box on a button click. once you press Yes we use our old friend javascript method __doPostBack(controlName, ”) to continue server side execution.

Please note that in __doPostback method second parameter is empty string,  If you need to pass some arguments while enforcing a postback. convert it to a Json string and pass it to code behind. You can convert this json string to C# object using Javascript serializer. 
Please refer to my article on json string to C# coversion http://wp.me/p1hH3Q-2E

I hope it is useful!

Advertisements