jQuery UI Dialog shown using an ASP.NET button - c#

I'm trying to show a modal dialog when the user click on an ASP.Net button. This is my page:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="js/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.6.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 300,
modal: true,
buttons: {
'Ok': function() {
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
},
close: function() {
;
}
});
});
function ShowDialog() {
$('#dialog').dialog('open');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="TreeNew" runat="server" Text="New" OnClientClick="ShowDialog();"/>
<asp:Label ID="Message" runat="server"></asp:Label>
<div id="dialog" title="Select content type">
<p id="validateTips">All form fields are required.</p>
<asp:RadioButtonList ID="ContentTypeList" runat="server">
<asp:ListItem Value="1">Text</asp:ListItem>
<asp:ListItem Value="2">Image</asp:ListItem>
<asp:ListItem Value="3">Audio</asp:ListItem>
<asp:ListItem Value="4">Video</asp:ListItem>
</asp:RadioButtonList>
</div>
</div>
</form>
</body>
</html>
When I click on TreeNew button appears modal popup but inmediately the page do postback.
What's happening?

While adding a return false; will fix your problem (as suggested by other answers), I think the best thing for you to do is use a standard HTML button. There is no reason to use an ASP.NET control in this case since you do not intend to postback.
If you insist to use a ASP.NET button, however, at least set UseSubmitBehavior="False" so that the button is rendered as <input type="button"/> instead of <input type="submit"/>.

Try
OnClientClick="return ShowDialog();"
AND
function ShowDialog() {
$('#dialog').dialog('open');
return false;
}
This will prevent the postback.

Your OnClientClick needs to return false like so:
OnClientClick="ShowDialog(); return false;"
Buttons by default postback but return false prevents the default behavior

You're not returning false from your OnClientClick. When you don't explicitly return false, "true" in this situation is assumed. A return value of true from your OnClientClick indicates it's fine to do a postback. Try changing OnClientClick to the following (adding "return false" after your call to ShowDialog())
OnClientClick="ShowDialog();return false;"

This article maybe of some value to you: using-jquery-modal-dialog-confirmation-with-an-asp-net-server-control.
Hope this helps some.

Use preventDefault() jQuery function to prevent button postback
Try this:
function ShowDialog(evt) {
evt.preventDefault();
$('#dialog').dialog('open');
}

Related

implementing jquery ui dialog into .net form

I'm using an out of the box implementation of JQuery UI Dialog on a .net form:
<form id="form1" runat="server">
<asp:Button ID="btnTest" runat="server" Text="Open Me"
onclick="btnTest_Click" />
<div id="dialog" title="Dialog Title">I'm a dialog</div>
<script>
$("#dialog").dialog(
{ autoOpen: false });
$("#btnTest").click(function () {
$("#dialog").dialog("open");
});
</script>
</form>
I have two questions. First, I want the content of the dialog to be dependent on some logic that happens after the button click event is processed in the codebehind. How can I do that?
Second, just testing it above in demo mode, fires the dialogue but immediately closes it. I'm assuming it has something to do with e.preventDefault(), or thats what I've read, but I'm not sure how that will factor in if I tie it to run after the postback of the form.
To call the server you will need to make an Ajax call to get the data you need to display:
$('#dialog').dialog({
autoOpen : false,
width : 500,
height : 400,
resizable : true,
modal : true,
open : function()
{
jQuery.ajax({
type : "POST",
url : //"post Url ex. Default.aspx/OpenDialog",
data ://data to send to the server,
dataType://the data type,
success : function(response)
{
$('#dialog').html(response);
},
error : function(xhr, ajaxOptions, thrownError)
{
alert("Error: " + thrownError + "Status: " + xhr.status);
}
});
},
buttons : {
"Close" : function()
{
$(this).dialog("close");
}
}
});
and in your button click you will do :
$("#btnTest").click(function () {
$("#dialog").dialog("open");
});
We can use ScriptManager.RegisterStartupScript in the code behind button click event. Then we can have a javascript function in the aspx page which actually has the dialog logic.
ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "myFunction();", true); //in code behind file
function myFunction(){
// update something to dialog div
$("#dialog").dialog(
{ autoOpen: false }
);
$("#dialog").dialog("open");
}
You want some value from code behind to front end?
if yes:
then at code behind :
protected void Button1_Click(object sender, EventArgs e)
{
HiddenField1.Value = " from code behind";
ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "myFunction('Hello');", true);
}
and at aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<style>
body {
font-family: "Trebuchet MS", "Helvetica", "Arial", "Verdana", "sans-serif";
font-size: 62.5%;
}
</style>
<script>
function myFunction(a) {
$("#dialog").text(a+$("[id$=HiddenField1]").val());
$("#dialog").dialog();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="dialog" title="Basic dialog">
</div>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
</html>
Hope it may help you.

Popup form changing textbox value only once

I have an asp page which calling another popup page on button click event. and few values are returned from the popup page by following code.
function ShowSelfpopup() {var customizeParamGL = 'status:no;help:no;dialogWidth:600px;dialogHeight:550px;scrolling=no';
var FunctionID = document.getElementById("ctl00_contPlcHdrMasterHolder_LstxtHidFUNCTION_ID").value;
window.showModalDialog('corBrmBlockIssuAndMaintFindUI.aspx?Function_Id=' + FunctionID + '', window, customizeParamGL);
debugger;
if (XYZ_PID != '') {
debugger;
document.getElementById("ctl00_contPlcHdrMasterHolder_LsddlProductID99").value = XYZ_PID;
document.getElementById("ctl00_contPlcHdrMasterHolder_LstxtStartNo").value = XYZ_SN;
document.getElementById("ctl00_contPlcHdrMasterHolder_LstxtEndNo").value = XYZ_EN;
document.getElementById("ctl00_contPlcHdrMasterHolder_lstxthide").value = XYZ_BP;
aspnetForm.submit();
return true;
}
else {
return false;
}
}
Now I have a Text changed event method for LstxtEndNo. Which is firing only first time I am getting data from the popup form. next time I'm calling the popup form and getting data as i confirmed by debugging. but its neither changing values in the textbox nor firing text changed event.
For Javascript Dont use Textchange event instead onchange
<head runat="server">
<title>
</title>
<script>
function AlertTest()
{
alert('hELLO');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </ajax:ToolkitScriptManager>
<div>
<asp:TextBox ID="Button1" runat="server" Text="Button" onchange="AlertTest()" />
</div>
</form>
</body>
Try this with your example

How to call a javascript function before and after button click event call in asp.net

i have created "ButtonClick" function in ASP.NET as following:
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click"/>
i want to know, is it possible to call a javascript function before and after calling asp.net button click function...???
Thanks.
Yes it's possible, here is quick example:
Java script function to call.
<script type="text/javascript">
function clientValidate() {
alert("execute before");
return true;
}
function executeAfter() {
alert("execute after");
}
</script>
Here is snapshoot for button
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="clientValidate()" onclick="btnLogin_Click"/>
Notice property onClientClick="clientValidate()", it will be trigger script before button click on the server.
On the server side:
protected void btnLogin_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", "<script>executeAfter();</script>", false);
}
Notice executeAfter();, it will trigger javascript execution after server event.
Don't forget to place <asp:ScriptManager runat="server"></asp:ScriptManager> in your aspx file.
Hope it help
put this on your page and make sure you have a scriptmanager. these codes will handle your pre & post postbacks.
var prm, postBackElement;
if (typeof Sys != "undefined") {
prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
}
function InitializeRequest(sender, e) {
postBackElement = e.get_postBackElement();
if (postBackElement.id == "btnLogin") {
// before click codes
}
}
function EndRequest(sender, e) {
if (postBackElement.id == "btnLogin") {
// after click codes
}
}
Before:
<script type="text/javascript">
function executeBefore() {
alert("execute before");
}
</script>
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="executeBefore()" onclick="btnLogin_Click"/>
After:
<script type="text/javascript">
function executeAfter() {
alert("execute after ");
}
</script>
Add this code to your server side event:
Page.ClientScript.RegisterStartupScript(GetType(), "none", "<script>executeAfter();</script>", false);
If you don't have a master page, or are not using ajax, there is no need to add ScriptManager.
You can call Java scrip function before server side click using OnClientClick():
aspx(design)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Test() {
alert('client click');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="btn" runat="server" ID="btn"
OnClick="btn_Click" OnClientClick="Test()" />
</div>
</form>
</body>
</html>
.cs
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("Server Click");
}
First time you can call your javascript function in Button's OnClientClick event passing your function name.
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click" OnClientClick="return functionNAME();"/>
Second time, in your button click event btnLogin_Click call js as follow
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "script", "<script type='text/javascript'>functionNA();</script>", false);
For calling it before, you could consider using onload function, like this example:
<body onload="myFunction()">
For calling it afterwards, just link the button to execute JS onClick?
I don't think I quite understand your intentions.

Javascript function is not working on asp:button Click event, where a test alert function works.!

I am trying to create an alert as described in this site http://needim.github.com/noty/
and here is the code
<head runat="server">
<title>Test</title>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/noty/jquery.noty.js"></script>
<script type="text/javascript" src="js/noty/layouts/top.js"></script>
<link rel="stylesheet" type="text/css" href="buttons.css" />
<script type="text/javascript" src="js/noty/themes/default.js"></script>
</head>
<body>
<div class="container">
<div id="customContainer">
</div>
</div>
<script type="text/javascript">
function generate(type, layout) {
var n = noty({
theme: 'defaultTheme',
text: 'Do you want to continue?',
buttons: [
{
addClass: 'btn btn-primary',
text: 'Ok',
onClick: function ($noty) {
// this = button element
// $noty = $noty element
$noty.close();
noty(
{
text: 'Record deleted !',
type: 'success',
callback:
{
onShow: function () { },
afterShow: function () { TakeValue(true); },
onClose: function () { },
afterClose: function () { }
}
});
}
},
{
addClass: 'btn btn-danger',
text: 'Cancel',
onClick: function ($noty) {
$noty.close();
noty(
{
text: 'Record not deleted !',
type: 'warning',
callback:
{
onShow: function () { },
afterShow: function () { TakeValue(false); },
onClose: function () { },
afterClose: function () { }
}
});
}
}
]
});
}
function TakeValue(result) {
if (result == true) {
document.getElementById("Hidden1").value = "true";
alert(document.getElementById("Hidden1").value);
} else {
document.getElementById("Hidden1").value = "false";
alert(document.getElementById("Hidden1").value);
}
}
function generateAll() {
generate('information', 'top');
}
</script>
<form id="form" runat="server">
<input id="Hidden1" type="hidden" value="false"/>
<asp:Button ID="Button2" runat="server" Text="Press" OnClientClick="return generateAll();" />
<input id="Button1" type="button" value="button" onclick="return generateAll();" />
</form>
</body>
I have placed two buttons ,one is HTML button while the other is of asp:Button,
The whole scenario just works fine when I use the HTML button ,but the page is not displaying the similar behavior in case of asp:Button click, I have placed a test function in JavaScript to test the OnClientClick event of the asp:Button and that worked fine,but I don't know why this alert is not getting called, I think there is some problem with the Noty JS.
Kindly give feed back
thanks.
As jbabey said in the comments:
an asp:button will cause a postback when clicked by default. you need to return false from the onclientclick, right now you are returning undefined since generateAll has no return.
Since you're using jQuery, I'd go one step further and not directly set the click attribute. Instead, set it using jQuery:
<script>
$(document).ready(function() {
$('#Button1').click(generateAll);
});
...
function generateAll(e) {
generate('information', 'top');
// This will prevent the default action of submitting the form.
e.preventDefault();
}
</script>
Could you please add UseSubmitBehavior="false" attribute to the asp:button.
<asp:Button ID="Button2" runat="server" Text="Press" UseSubmitBehavior="false" OnClientClick="return generateAll();" />
I hope this will resolve your issue. Please let me know whether it helped you or not.

jQuery in .net validate dropdownlist, fadein and fadeout panels

I have a dropdownlist control ddlAffilation, a panel pnlForms, a panel Complete, a button Submit, a button Return.
I have a validationcontrol on the dropdownlist.
here is my jquery code
<script type="text/javascript">
$(document).ready(function () {
$("#<%= Submit.ClientID %>").click(function () {
$("#<%= pnlForms.ClientID %>").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
});
$("#<%= Return.ClientID %>").click(function () {
$("#Complete").fadeOut('slow');
$("#<%= pnlForms.ClientID %>").delay(800).fadeIn('slow');
});
});
</script>
I have 2 problems:
1) With this jQuery code, I can go back and forth (fade out pnlForms, fade in Complete when click on Submit and vice versa when click on Return) only when i don't choose any value in the dropdownlist box. If I choose any value in the dropdownlist, the Return button doesn't work.
2) The jquery code bypass the .net server validation control. I need the code not do anything if no value is selected from the dropdownlist. I have tried
var isValid = true;
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
isValid = false;
return false;
}
if (isValid == true) {
...
but it doesn't work. What's the best way to do this?
Thanks,
==================================================================================
I can't add an answer to my own question so I reply to John here:
Thanks John. I have my code like this and it solves problem 2.
<script type="text/javascript">
$(document).ready(function () {
$("#<%= Submit.ClientID %>").click(function (e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
else {
$("#<%= pnlForms.ClientID %>").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
}
});
$("#<%= Return.ClientID %>").click(function () {
alert('blah2');
$("#Complete").fadeOut('slow');
$("#<%= pnlForms.ClientID %>").delay(800).fadeIn('slow');
});
function IsValid() {
// Add any other validation in here
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
return false;
}
return true;
}
});
</script>
However, problem 1 still exists. Let me clarify. I have a few textboxes, a dropdownlist and a submit button to collect feedback from the users. They are all in the panel pnlForms.
All controls can be empty except for the dropdownlist. We took care of this using your code and a server validation control.
when the users click the submit button, I want the pnlForms to fadeOut and a hidden panel called pnlComplete to fadeIn. The pnlComplete has a text saying thanks for the feedback and a button called Return that let the users send another feedback.
When the users click on the Return button, the opposite happens here. The pnlComplete fadeOut and the pnlForms fadeIn.
The Submit button works well but the Return button doesn't work at all. I set some alert() inside the Return.click(function but it doesn't hit.
Any ideas?
Here is the code of the whole page.
<%# Page Title="" Language="C#" MasterPageFile="~/Master.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="content" runat="Server">
<asp:UpdatePanel ID="pnlForms" runat="server">
<ContentTemplate>
<fieldset>
<legend>Your Information</legend>
<ol>
<li>
<label for="ctl00_content_name">
Your Name:</label>
<asp:TextBox ID="Name" runat="server" Width="150px"></asp:TextBox>
<em class="optional">Optional </em></li>
<li>
<label for="ctl00_content_status">
Your Affiliation:*</label>
<asp:DropDownList ID="ddlAffilation" runat="server" Width="155px">
<asp:ListItem Text="--Select One--" Value="" Selected="True" />
<asp:ListItem>F</asp:ListItem>
<asp:ListItem>S</asp:ListItem>
<asp:ListItem>T</asp:ListItem>
</asp:DropDownList>
<em class="required">Required
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage=" - Please select your affiliation"
ControlToValidate="ddlAffilation" SetFocusOnError="True" ForeColor=""></asp:RequiredFieldValidator>
</em></li>
</ol>
</fieldset>
<div style="text-align: center;">
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="submit_Click" /></div>
</ContentTemplate>
</asp:UpdatePanel>
<div id="Complete" style="display: none;">
<asp:UpdatePanel ID="pnlComplete" runat="server">
<ContentTemplate>
<p>Thank you</p>
<div style="text-align: center;">
<asp:Button ID="Return" runat="server" Text="Return" /></div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
<asp:Content ID="Content3" runat="server" ContentPlaceHolderID="cpClientScript">
<script type="text/javascript">
$(document).ready(function () {
$("#<%= Submit.ClientID %>").click(function (e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
else {
$("#<%= pnlForms.ClientID %>").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
}
});
$("#<%= Return.ClientID %>").click(function () {
$("#Complete").fadeOut('slow');
$("#<%= pnlForms.ClientID %>").delay(1000).fadeIn('slow');
});
function IsValid() {
// Add any other validation in here
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
return false;
}
return true;
}
});
</script>
</asp:Content>
I'm not sure if I read your question right or not, but if your issue is that you don't want the jquery to continue firing and allow the form to submit if the dropdown is empty do this:
Instead of attaching a .click event to your button, attach a .submit event to your form. Then you want to use e.PreventDefault() to stop the main submit execution if its not valid
Eg:
$("#FORMNAME").submit(function(e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
// Submitting form...
}
function IsValid() {
// Add any other validation in here
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
return false;
}
return true;
}
Also, you should ALWAYS do server validation along with your client validation.. otherwise all someone has to do is directly submit / bypass your javascript checks
Edit for your edit:
Is the return button being created dynamically or is it there on page load? If its dynamic, its probably never getting assigned to in your jquery, as it doesn't exist when it runs.
Here is a quick test you could try:
var returnButton = $("#<%= Return.ClientID %>");
alert(returnButton.attr("id");
If you don't get back the ID of your return button, its not matching up in your code and thats why your click event isn't working. If thats the case, do a view source on your page and find out what the actual return button ID is set to (this is easier with FireBug or similar tool)
Adding this as a separate answer since its just a huge chunk of code that isn't exactly related to the original answer, but does work as intended. I took the code you gave and converted to basic html from asp.net, and it does work correct, does it work for you?
Could you try posting the output from the asp.net page instead of the code itself? Maybe something isn't being set right on the button element's ID.
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js" type="text/javascript"></script>
</head>
<body>
<div ID="Content1">
<div ID="pnlForms">
<fieldset>
<legend>Your Information</legend>
<ol>
<li>
<label for="ctl00_content_name">
Your Name:</label>
<textbox ID="Name" runat="server" Width="150px"></TextBox>
<em class="optional">Optional </em></li>
<li>
<label for="ctl00_content_status">
Your Affiliation:*</label>
<select ID="ddlAffilation" Width="155px">
<option Value="" Selected="True">--Select One--</option>
<option>F</option>
<option>S</option>
<option>T</option>
</select
</li>
</ol>
</fieldset>
<div style="text-align: center;">
<Button ID="Submit" Value="Submit" OnClick="submit_Click">Submit</Button></div>
</div>
<div id="Complete" style="display: none;">
<div ID="pnlComplete">
<p>Thank you</p>
<div style="text-align: center;">
<Button ID="Return" Value="Return">Return</Button></div>
</div>
</div>
</div>
<div ID="Content3">
<script type="text/javascript">
$(document).ready(function () {
$("#Submit").click(function (e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
else {
$("#pnlForms").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
}
});
$("#Return").click(function () {
$("#Complete").fadeOut('slow');
$("#pnlForms").delay(1000).fadeIn('slow');
});
function IsValid() {
// Add any other validation in here
if ($("#ddlAffilation").val() == "") {
return false;
}
return true;
}
});
</script>
</div>
</body>
</html>

Categories

Resources