I have an aspx page with ajax panel on it and a button.
this is my button :
<asp:Button ID="Button1" runat="server" OnClientClick="javascript:SetValues()" onclick="Button1_Click" Text="Button" />
when I click on the button I call the SetValues() function on the OnClientClick event. this function will change the position of the div on the screen.
the Button1_Click method is running on the server and loading the div with data.
The problem is that the work that "SetValues()" did is canceled because the div after comming back from the server, is going back to it's original position on the screen.
What are you trying to make happen server side? Have you considered doing an ajax postback to send/process your data on the server? This will allow your client side JS to change the UI, while the server receives and process your data.
Check out this article for more information on using jQuery to trigger server side processing.
One option would be to call SetValues() after the ajax panel has updated (I'm assuming you are using an UpdatePanel here).
<script type="text/javascript">
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined)
{
SetValues();
}
else
{
alert("There was an error" + args.get_error().message);
}
}
function load() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
</script>
You will need to fire the load function when the page has loaded to register for the Javascript event.
<body onload="load()">
Use a hidden server control and read/write values from the hidden control. Values will be persisted across post back.
Related
I wonder if there is way to run JS code whenever a asp.net page is contacting the server.
I.e. I'm looking for a general event handler that is triggered whenever a call to the server is made for runat="server" components.
I know there's a way to get jQuery.ajax() to run JS code before and after a call to the server is made, but I'm not sure how to do it in asp.net. Especially, since this projects uses a lot of custom components.
The goal here is to show some kind of loading image when a button is clicked, to prevent the user to click a button twice and also to show the user that the system is working.
If the click causes the page or an updatepanel to refresh, I'd only like to display the loading image before the refresh, eg. User clicks, "loading" is shown, page/update panel is refreshed (causing the "loading" to disappear), the new page/content is displayed as normal.
Update 1:
I can't use UpdateProgress because some of the buttons aren't inside UpdatePanels. What I really want to do is to fire a JS as soon as any button/control that will contact the server is clicked. I.e. if the user clicks a dropdown which doesn't contact the server, nothing should happend. But if that dropdown has any connection to the server, a JS should be run.
I understand that this is ASP.NET Ajax and not jQuery Ajax, I only used jQuery as an example. Because I've used a jQuery method before (with jQuery Ajax) to trigger JS before the server call was made. Eg. to lock the element that was clicked or to display a "Loading..." screen.
I could of course add a bit of a JS hack to every page which adds a "onclick" event to every button manually, but I thought it would be better if there was a general solution for this (since I've got lots of pages, each with a few buttons that contact the server on them).
Update 2:
When I think about it, it doesn't necessarily need to be a JS that is triggered. It would be good enough if the page somehow only made sure that the same button wasn't clicked twice. Either by disabeling the button or by adding something in front of it (like a "Loading..." screen).
You can use an UpdateProgress for this to use with update panels, but if you are doing a full page postback (i.e. not ajax) the only loading animation you can have is the browsers own.
UpdateProgress:
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
Shiny loading aninmation
</ProgressTemplate>
</asp:UpdateProgress?
Here is how you can do it using jquery:
$(function() {
$('a[href]').on('click', function(e) {
var self = this;
e.preventDefault();
loadAsync($(self).attr('href'));
});
});
function loadAsync(url) {
$('div#result').fadeOut(200, function() {
$('div#loader').fadeIn(200, function() {
$.get(url, function(data) {
$('div#result').html($(data));
}).done(function() {
console.log('done');
}).fail(function() {
$('div#result').html('Error');
}).always(function() {
$('div#loader').fadeOut(200, function() {
$('div#result').fadeIn(200);
});
});
});
});
}
When a user clicks a button on ASP.net page, I need to
Save file from asp:fileUpload in a folder on a server - I guess this needs to be done in C#, like in How to correctly use the ASP.NET FileUpload control
Run a javascript function like in How to call javascript function from asp.net button click event
Is there a way to combine C# and Javascript to achieve what I need? If not, how should I do it?
Try using the onClientClick property of the asp:button element.
Ex, on your .aspx file:
<script type="text/javascript">
function myFunction()
{
alert('hi');
}
</script>
...
<asp:button id="Button1"
usesubmitbehavior="true"
text="Open Web site"
onclientclick="myFunction()"
runat="server" onclick="Button1_Click" />
And in your code behind (.aspx.cs)
void Button1_Click (object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
More info at
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
Note that no JavaScript actually "runs" until the server-side code (C# in this case) has entirely completed and the resulting page is returned to the client. Once that page renders on the client, then JavaScript runs on the client.
So in order to execute your JavaScript code, all you need to do is include it in the page being returned to the client. There are a number of ways to do this, and the options depend on whether you're using WebForms or MVC.
You might use something like RegisterStartupScript in WebForms, for example. Or, you could just have the JavaScript code exist in a PlaceHolder control with Visible=false and only make the control visible in the response which intends the JavaScript code to run. (Roughly the same method is also easily usable in MVC by just wrapping the JavaScript code in a server-side condition to determine whether to render it or not.)
The main thing to remember is that you're not "running the JavaScript code from C#" or anything like that. There's a hard separation between server-side and client-side code. The server-side code ultimately builds the page that it sends back to the client, and that page can include JavaScript code to run on that client.
protected void addSchoolButtonClick(object sender, ImageClickEventArgs e)
{
Page.ClientScript.RegisterStartupScript(GetType(), "MyKey1", "SchoolSearchPopUp();", true);
/*Some code*/
}
I am developing a website in asp.net.At a Hyperlink onclick event i want to call a javascript function"SchoolSearchPopUp()".this function is for creating a new popup window and it is working correctly.But my problem is ,a javascript function is calling or pop window opens only after executing the rest of the code in that function and that code need's some data that occurs as a result of popup.How can i create the popup before executing the rest of code in that function.
Change your postback trigger to something within the popup.
I don't think javascript can be called from code behind. C# is running from the server and java is all client side. There's a good explanation to a similar question here: http://forums.asp.net/t/1117189.aspx
If you need to execute a javascript function, you could try changing the hyperlink to a button and making use of the OnClientClick property. This executes script client side rather than calling a method on the server.
<asp:button id="Button1"
text="Click Here"
onclientclick="SchoolSearchPopUp()"
runat="server" />
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
You will need to write JavaScript on the page to handle the click of the button first and then call to the page method on the server.
Add an OnClientClick attribute to your button element and run your JavaScript method from there:
<asp:Button ID="TestButton" OnClientClick="SchoolSearchPopup()" Text="Click Me" OnClick="addSchoolButtonClick" runat="server"/>
<script type="text/javascript">
function SchoolSearchPopup()
{
alert("Popup");
}
</script>
If you want to execute some javascript before your postback you will need to register your hyperlink's click event to a js method, then submit your post to the server after performing whatever client side logic you are looking to run. (not the other way around, using RegisterStartupScript)
Example:
$("#myHyperLink").click(function() {
// do page logic, in your case show a modal window
$("#myModalDivContainer").show();
// submit your post to the server... replace targetClientID with ID of server control you're posting to
__doPostBack('targetClientID', '');
// NOTE: If you want to perform an AJAX request instead simply use some jQuery here instead. it's up to you how to handle the request from this point :)
});
Hope this helps!
I am using ASP.Net AJAX UpdatePanel to load the right part of the page.
As that part will take some time to load, I would like to load it after the other parts of the page is loaded.
I can use either normal AJAX or ASP.Net AJAX but I chose to use the latter as I want to try it out.
I found out that my UpdatePanel is always loaded.
I want it to be loaded only after the page is ready.
Some says to use the timer, some says to use some javascript.
But I still can't get it done.
So, these are my 2 obstacles, to stop loading when the page starts and to start loading when the page is ready
why don't you enable and disable on page events? for example. try in Page_PreLoad event, set the update panel's enable property to False. While in Page_LoadComplete event, set it back to enabled = true
UpdatePanels use Ajax to update, not on first load.
If you want it to load quickly on first load, avoid any expensive processing, database calls on load. Put them in an
if(IsPostBack)
{
//your long processing
}
Now use an AsyncPostBackTrigger to make your updatePanel postback.
try with this code ( Conditional Mode + Update Method)
<asp:UpdatePanel ID="YourIdPanel" UpdateMode="Conditional" runat="server">
//In order to force loading
YourIdPanel.Update();
<script type="text/javascript">
var currentItemID=$('#<%= labcurrentItemID.ClientID %>').html();
if (currentItemID != null) {
$(document).ready(function () {
$('#main_container').load('/Custom/Going%20Places/PopularRelatedArticle.aspx?currentID=' + currentItemID);
});
}
else {
$(document).ready(function () {
$('#main_container').load('/Custom/Going%20Places/PopularRelatedArticle.aspx?currentID={7F0811A7-D484-4675-8A23-0AEB235B9B5F}');
});
}
</script>
Hi everyone I have a web form in which I am having a button on clicking which data back up is being taken, I used the following javascript :
<script language="javascript" type="text/javascript">
function showPleaseWait() {
document.getElementById('PleaseWait').style.display = 'block';
}
</script>
<asp:Button ID="btnTakebackup" runat="server" Text="Take Backup" Enabled="true"
onMouseDown="showPleaseWait()" CausesValidation="false" />
<div id="PleaseWait" style="display: none;">"Please Wait Backup in Progress.."</div>
Hi I am using a button to take a back up.
Now I want to show a message in btnTakebackup_Click() event, whether Back up was successful or not.
I used Response.Write("<script>alert('abcd');</script>"); in btnTakebackup_Click() event.
But the problem is that I want to show the page also, which is not showing instead white background is showing.
Thanks in advance...
To show a message box alert should be able to write out a new script to the response stream:
var script =
"<script type=\"javascript\">" +
"alert(\"Backup in progress, don't go!\");" +
"</script>"
Response.Write(script);
However much this is distasteful, I suppose it is sometimes "necessary".
You can add client side event handlers to ASP controls:
How to: Add Client Script Events to ASP.NET Web Server Controls
Cheers.
Do you really want it to be an alert? (You should know that they lock up the whole browser not just the tab your page is on), do your users really need to acknowledge the backup success by clicking ok or just be informed of it?...
I suggest you have a div on the page that says "Backup successful". The visibility of which can be set by a boolean property BackUpSuccess which you can set to true in the code behind you mention.
<div id="backUpSuccess" <%=BackUpSuccess ? "" : "style='display:none;'"%>>
Backup was successfull
</div>
...you can style the div as you like in your .css file to get attention.
If you really do want an alert you could run some JavaScript on page load to check the content of a hidden input that you set server side in similar fashion...but running javascript on page load is tricky...unless your using jQuery and then you will know it's very easy.
From your question, I understood that after clicking on the button, the data back up is happening, but the alert is not displaying as soon as you clicked the button.This is because you are calling the JavaScript in the button click event which will be fired only after all the code in the button click is executed.I suggest you to add a JavaScript function in the .aspx source page it self and call the JavaScript function as shown below:
<script ...>
function xyz()
{
alert('Please Wait');
}
</script>
and in button declaration
<asp:button id='btn_submit' runat="server" OnClientClick="return xyz();" />