I have the following ASP.NET markup:
<div id="myForm" title="My Form" style="display: none">
<span>You can see me!</span>
<div style="display: none">
<asp:Button ID="btnSave" runat="server" Text="Button"
OnClick="btnSave_Click" />
</div>
</div>
<!-- called by an element click event elsewhere -->
<script type="text/javascript" language="javascript">
$("#myForm").dialog({
modal: true,
width: 500,
height: 200,
resizable: false,
buttons: {
"Cancel": function () {
$(this).dialog("close");
},
"Save": function () {
$(this).dialog("close");
// I want to call btnSave_Click (by DOM-clicking the button?)
}
}
});
$("#myForm").parent().appendTo("form:first");
</script>
I'm trying to get the jQuery.dialog generated buttons to perform the postback in place of the ASP.NET button. What should I do to make the button do a submit and call the btnSave_Click method?
EDIT
"Save": function () {
$(this).dialog("close");
document.getElementById("<%=btnSave.ClientID %>").click();
}
... works but is this the best solution?
$("#<%=btnSave.ClientID %>").click();
You can use the btnSave.ClientId property to emit to the javascript the ID of the control you are looking for, then you can do something like this. This is if you want the btnSave control to register as a postback control, triggering the "Click" event in the code behind.
var myControl = document.getElementById('theclientidgoeshere')
myControl.click();
That will do it!
If you want to do a simple postback you can do
this.document.form.submit();
but that will NOT register any events for the button.
Is This Best?
For .NET 3.5 and earlier it is the only "truly" safe ways to get the client ID. With jQuery you could do a partial id match on _btnSave, but I find that that is too risky for future modifications.
.NET 4.0 does introduce an option that might help.
.NET 4.0 ClientIDMode Property
In .NET 4.0 you have an optional ClientIDMode Property that will allow you to choose how the client id is created. You can use Predictable or Static options to allow you to hard-code the id of the button into your JavaScript.
Related
I have a formview which launches in editmode and allows the user to select yes or no from a dropdown and hit the 'save' button which is the Formviews Update command:
<asp:FormView ID="FormView1" runat="server" DataSourceID="CustomerEdit">
<ItemTemplate>
hello
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="CustomerNameLabel2" runat="server"
Text='<%# Bind("CustomerName") %>' />
<asp:Label ID="CustID" runat="server" visible="false"
Text='<%# Bind("CustID") %>' />
<br>
<br></br>
Is This Your Customer?
<br>
<br>
<asp:DropDownList ID="DropDownList1" runat="server"
SelectedValue='<%# Bind("IsThisMyCustomer") %>'>
<asp:ListItem Selected="True"></asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
<br>
<br>
<asp:Button ID="Button" runat="server" CausesValidation="True"
CommandName="Update" Text="Save" />
</EditItemTemplate>
</asp:FormView>
This button also has JQuery behind it
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("input[id$='Button']").click(function () {
var div = $("div");
$("img").hide();
div.animate({ height: '300px', opacity: '0.4' }, "slow");
div.animate({ width: '300px', opacity: '0.8' }, "slow", function () {
window.location.href = "MyCustomers.aspx";
});
});
});
</script>
Now when the user hits the button, the Jquery script kicks in, then about halfway through the animation of the jquery script, the SQL update through the FormView Update command kicks in, essentially stopping jquery from doing its stuff and launching the itemtemplate of the formview as per a regular update.
What I want is the SQL update to occur and postback, then the jquery fire straight after.
What's the best approach to doing this
You're mixing client-side and server-side functionality. The order of events you're observing is this:
Load the page
Bind the click event to the element
Click the element (begins the animation)
Reload the page
Bind the click event to the element
Your click event is really only accomplishing one thing, redirecting the user to another page. If the page is being reloaded anyway, then why not do that from server-side code?
Response.Redirect("MyCustomers.aspx");
It doesn't have the animation, but since you're reloading the page anyway then the animation is kind of moot. If you want to have the animation then you probably don't want to reload the page, in which case you'll want to start looking into AJAX for interacting with the server from JavaScript code. (Which can be a pretty big subject, especially when dealing with WebForms controls. It's often better in that case to just "do it the WebForms way" and not try to mess with them.)
In your comment above, you said you tried this...
$(window).load(function () { $(document).ready(function () { ...
That's... not right. Don't just randomly mix and match jQuery code, understand what it is you're doing here. You're binding events (such as ready) inside of an event handler (such as load), which can get pretty strange pretty fast. Separate the event you want to respond to from the code you use to respond to it. For example, consider what you have here:
$("input[id$='Button']").click(function () {
//...
});
This doesn't execute the code inside the function, it binds that function to be executed when the click event happens. The same is true of this structure:
$(document).ready(function () {
$("input[id$='Button']").click(function () {
//...
});
});
This binds a function to be executed when the ready event happens. That function, in turn, binds another function to be executed when the click event happens.
Consider for example what I mentioned in my comment above... If you really want to animate the element and then redirect after the page reloads (which I still contend is a pretty poor UX, to be honest) then you would do this:
$(document).ready(function () {
var div = $("div");
$("img").hide();
div.animate({ height: '300px', opacity: '0.4' }, "slow");
div.animate({ width: '300px', opacity: '0.8' }, "slow", function () {
window.location.href = "MyCustomers.aspx";
});
});
This skips the click event and just sets that code to execute immediately on the ready event. Which means it'll execute when the page loads, basically. Which also means that you don't want to always include this in the page (otherwise you'd never be able to view the page for more than a moment). You'd want to only include it dynamically from the post-back which should cause this redirect.
Ultimately, you need to separate your client-side functionality from your server-side functionality. If you're just redirecting after a form post (which is what you're doing), then redirect from server-side code. If you want the bells and whistles of client-side animations and UX, don't use WebForms post-backs.
I would like to have a nice pop up warning that says "Are you sure you want to overwrite this file? Yes No. Is there any way to do this with telerik or Ajax Tool Kit?. I want to be able to control it on the server side too with c#
Thank you
one way could be
1) create a div like a popup
2) display the popup when some events occurs (like button click)
3) if users click ok then doing somethings on server side
4) if users click no then hide the div
Here some code, sorry if there is some error but i don't have the environment on my hands.
<head>
<script type="text/javascript">
function showConfirm()
{
var popup = document.getElementbyId('popup');
popup.style.display = '';
}
function hide()
{
var popup = document.getElementbyId('popup');
popup.style.display = 'none';
}
</script>
</head>
<body>
<form runat="server" id="form1">
<div id="popup" style="display:none">
<p>bla bla bla</p>
<asp:button id="btn_ok" runat="server" OnClick="ServerRountine_Click"/>
<asp:button id="btn_ko" runat="server" onclientclick="hide();"/>
</div>
<asp:button id="btn_overwrite" runat="server" onclientclick="showConfirm();"/>
</form>
</body>
You can try:
jConfirm(message, [title, callback])
http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/
You can put an OnClick (or OnClientClick if it's a serverside control) event on your submit button like the following:
<input type="button" value="Submit new file" onclick="if(confirm('Are you sure you want to overwrite this file?')) return false;" />
I'd prolly use asp modalpopup for this ;p
... but yeah you want to do it with ajax etc.
I think you'd love jq-ui then.
It is almost the same as above , but it will style the popup at the same time;p
$("#modEdit").dialog({//modEdit is your Div with any controls.
autoOpen: false,//Properties
width: 600,
show: "fade",
hide: "fade",
modal: true,
buttons: {//Buttons
"Save Changes": function () {
ModSaveChanges();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
Syntax looks in short like this $(control).dialog({properties,buttons:{btn1,btn2}}); etc
really easy, I really recomend it ^^ :D
I have used it for my Mobile Apps;p
Oh and you might also then take a look into Sencha Ext ;p
I am trying to add a few functions to a ASP.NET page using jQuery UI's dialog. I am attempting to display 3 separate dialogs which allow a user to add or edit a contact's address, phone, or email information.
I have a UserView page which contains the jQuery, a GridView, and the DIVs I load the controls into. I am using jQuery's .load(url + '#DIV', function... capability to load the 3 boxes from a second page called UserFunctions.
The boxes all load and are populated correctly with data, however, the save button does not submit the changes skipping the button's click command. Is there a way to do this? Can I manually call postback from the jQuery dialog? I would like to stay away from IFrames if at all possible.
UserView jQuery Code
$('#addPhone').load('/Administration/UserFunctions.aspx?Mode=edit&Record=1' + ' #PhoneAdd', function () {
$(this).dialog({
modal: true,
autoOpen: false,
draggable: true,
width: 600,
open: function (type, data) {
$(this).parent().appendTo("form:first");
},
buttons: {
"Close": function () { $(this).dialog("close"); }
}
});
});
UserView and Show Dialog Button
Add Phone<br /><br />
<div id="addPhone">
</div>
UserFunction DIV that is loaded
<div id="PhoneAdd">
<p><span class="Type">Phone Type
<asp:DropDownList ID="ddPhoneType" runat="server" Width="205px"
DataSourceID="odsPhoneType" DataTextField="PhoneName"
DataValueField="PhoneTypeID">
</asp:DropDownList>
<asp:ObjectDataSource ID="odsPhoneType">
</asp:ObjectDataSource>
</span></p>
<p><span class="Number">Number
<asp:TextBox ID="ttPhoneNumber" runat="server" Width="100" ></asp:TextBox></span>
<span class="Extension">Extension
<asp:TextBox ID="ttPhoneExtension" runat="server" Width="50" ></asp:TextBox></span></p>
<p><span class="PhoneSubmit"><asp:Button ID="btnPhoneSubmit" runat="server"
Text="Save" onclick="btnPhoneSubmit_Click" />
</span></p></div>
UserFunction Button Click Event (which does not fire)
protected void btnPhoneSubmit_Click(object sender, EventArgs e)
{
if (qString == "insert")
{ //insert to database. Code removed to save room. }
if (qString == "edit")
{ //update database}
}
The Code Behind above never runs (tested by attempted to debug the if statement).
Thank you in advance for your help. I appreciate it very much.
The problem here is, since you modal box are ajax requests they are not posting back to their respective pages but instead posting back to the parent page (UserView).
You could possibly handle this by putting a form in your modal and have it post to another page and handle the form inputs there.
<form action="/User/PostPhone.aspx" method="post">
//form elements in here
</form>
Then your PostPhone.aspx code behind will have do something like:
if (IsPostBack)
{
var phoneNumber = Request["phonenumber"];
//save phone number
}
so i have a lightbox in which pops up an aspx page with textboxes and two buttons (submit - disabled and cancel - enabled). I wanted to enable my submit button ontextchange. it works fine when opened separately (not as a lightbox) but when i let it run normally with the lightbox function everytime ontextchange gets triggered the whole page refreshes disabling the lightbox.
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="OnTextChanged_AttributesEdited" autopostback="true">
protected void OnTextChanged_AttributesEdited(object sender, EventArgs e)
{
btnSubmit.Enabled = true;
}
now if i take out the "autopostback=true" it then will not trigger the the ontextchanged. was wondering if is it better if javascript will be the way to go for enabling the button or is there a way where i can prevent the postback when ontextchanged is triggered?
thanks a lot!
I think this would be a prime use for some jQuery in your application. Without posting back to the server for enabling / disabling a button, this would look a lot smoother, load faster and keep your current page state intact. An example might be as follows:
<script type="text/javascript">
$(document).ready(function() {
$("#textBox1").change(function() {
$("#btnSubmit").removeAttr("disabled");
});
});
</script>
Just put the above script tag in your HTML, just before closing the body tag.
An even better solution, however, would be to assign a specific CSS class to all the textboxes that should inherit that behaviour. Assuming that you assign a CSS class called "someCssClass" to all those textboxes, your script would then look something like this:
<script type="text/javascript">
$(document).ready(function() {
$("input.someCssClass").change(function() {
$("#btnSubmit").removeAttr("disabled");
});
});
</script>
I'd use jQuery as mentioned by #FarligOpptrenden, but if you don't have it and just want plain javascript, this should work.
Input within your lightbox:
<input type="text" id="textbox" onKeyUp="enableSubmitButton()" />
<input type="button" id="submitButton" value="Submit" />
<input type="button" id="cancelButton" value="Cancel" />
Javascript:
<script type="text/javascript">
function enableSubmitButton()
{
document.getElementById('submitButton').disabled = false;
document.getElementById('cancelButton').disabled = true;
}
</script>
You could also do your enabling/disabling buttons on load in javascript:
<script type="text/javascript">
window.onload = function () {
document.getElementById('submitButton').disabled = true;
document.getElementById('cancelButton').disabled = false;
}
</script>
I have the following ASPX 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');
__doPostBack('TreeNew', '');
},
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="Nuevo" OnClientClick="ShowDialog(); return false;"/>
<asp:Label ID="Message" runat="server"></asp:Label>
<div id="dialog" title="Create new user">
<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 the user click on TreeNew button appears the modal dialog, then he/she choose an option an click Ok button to do a postback.
I need that the server side execute TreeNew_Click method: How can I do that?
If I use __doPostBack('TreeNew', '') it throws me the following error: "Object expected".
UPDATE:
I found the origin for the error: the function __doPostBack is not defined. I'm not going to delete the question because I think Chris Clark's answer is so interesting.
As a rule, if you find yourself ever typing the text "__doPostBack(...", you should re-evaluate your approach.
In this case, you should just put a server-side asp.net button inside the div that you are turning into the dialog and use that instead of the generates jQuery button. That way the postback code will get wired up for you. There is one caveat however - when jQuery turns your div (I'm going to assuming it's a div) into a dialog, it rips the div out of the form element. That means you have to attach it BACK to the form BEFORE the postback occurs. You can do that in the close function of the dialog. The postback will then occur properly.
If you really want to use the generated jQuery OK button, you have a couple of options. First, you can slap a server-side asp.net button on the page and hide it, then call the asp.net button's click event from the OK button's code. Second, you can emit a javascript function form the server using Page.ClientScript.GetPostBackEventReference that will contain the __doPostBack code that you were trying to hand-write above. Then call that emitted function from the OK button's JS code.