Tuesday, September 16, 2014

How to use ASP.NET Button inside a jQuery Dialog box ?

Posted in , , ,


This is a problem which most of the Developers face who works with the ASP.NET and jQuery..

Lets assume that you have a jQuery Dialog box in your ASP.NET application which contains a ASP.NET Button. Sometimes you may experienced this kind of problem when you're try to run the page after writing all the codes.. Your jQuery Dialog box will appear without any problem. But when you are try to click on that ASP.NET Button you will realize that nothing will happen even you wrote the code for OnClick event. But it will work if you set Button's UseSubmitBehavior="false".

Problem solved ?
Actually No. Now the OnClick event will fire when you click on the button. But actually the problem is,
Assume that you have another ASP.NET Control inside the jQuery Dialog. Lets say a ASP.NET TextBox.

Here is the JavaScript code that invokes the jQuery Dialog and It's output :
//Display JQuery Dialog 
function showDialog(i) {

    $("#addReleaseDialog").dialog({
        draggable: true,
        resizable: false,
        width: 300,
        height: 410,
        minHeight: 10,
        minwidth: 10
    });

    return false;

}

Now your will need to use that TextBox's Text inside the Button's OnClick event. Will it work ? NO. It will return NULL value each and every time when you try access the Text of that TextBox. How can we solve this ?

The good thing is it's a simple fix. Here is the fixed code..
//Display JQuery Dialog 
function showDialog(i) {

    $("#addReleaseDialog").dialog({
        draggable: true,
        resizable: false,
        width: 300,
        height: 410,
        minHeight: 10,
        minwidth: 10
    });
    $("#viewReleaseDialog").parent().appendTo($("form:first"));
    return false;

}

What is the Reason ?
For the .Net postbacks to work, the JQuery dialog has to be added to the form. I believe it is separated so that JQuery dialog can control/lock the UI, handling custom buttons and preventing users from submitting other buttons (I may have this wrong, as it still successfully blocks the UI). Anyway, some internals of this system separates the form data and thus prevents .Net postbacks. Even forcing a postback by using 'UseSubmitBehavior=False' still prevents data being passed to the back end as it exists outside the .Net Form

That's all for today.. Happy coding..!!
If you gain some knowledge from this lesson and if you think this is useful leave a comment to encourage us. Good comments or bad comments all are important to usLets meet from a new lesson soon, have a nice day!!!

0 comments :