Disable page refresh after button click ASP.NET - asp.net

I have an asp button that looks like this:
Default.aspx
<asp:button id="button1" runat="server" Text="clickme" onclick="function" />
Default.aspx.cs
protected void function(object sender EventArgs e)
{
// Do some calculation
}
However, whenever I press the button, the entire page gets refreshed. I have looked on this site and found many solutions, but none of them really works for my project. Here are some of the suggested solutions:
set onclick="return false;" // but then how do I run the function in the code-behind?
use !IsPostBack in Page_Load // but the page still refreshes completely. I don't want Page_Load to be called at all.
Disable AutoEventWireup. // making this true or false doesn't make a difference.
Does anyone have a solution to this, or is it really impossible?

I would place the control inside of an Update panel.
To do so, you would also need a script manager above it, so something like this:
<asp:ScriptManager runat="server" ID="sm">
</asp:ScriptManager>
<asp:updatepanel runat="server">
<ContentTemplate>
<asp:button id="button1" runat="server" Text="clickme" onclick="function" />
</ContentTemplate>
</asp:updatepanel>
if a control inside the update panel does a postback, it will only reload the part of the page inside of the upate panel.Here is a link you may find useful from the MSDN site.

I think there is a fundamental misunderstanding here of how ASP.Net works.
When a user first requests your page, an instance of your Page class is created. The ASP.Net framework runs through the page lifecycle with this page instance in order to generate html. The html response is then sent to the user's browser. When the browser receives the response it renders the page for the user. Here's the key: by the time rendering is complete, your page class instance was probably already collected by the .Net garbage collector. It's gone, never to be seen again.
From here on out, everything your page does that needs to run on the server, including your method, is the result of an entirely new http request from the browser. The user clicks the button, a new http request is posted to the web server, the entire page lifecycle runs again, from beginning to end, with a brand new instance of the page class, and an entirely new response is sent to the browser to be re-rendered from scratch. That's how ASP.Net (and pretty much any other web-based technology) works at its core.
Fortunately, there are some things you can do to get around this. One option is to put most of your current Page_Load code into an if (!IsPostBack) { } block. Another option is to set up your method with the [WebMethod] attribute and make an ajax request to the method from the button. Other options include calling web services from custom javascript and ASP.Net UpdatePanel controls.
What works best will depend on what other things are on the page that user might have changed.

That is normal behavior for asp.net, you are actually causing a postback of the the page in order for the associated event to be called on the server.
I would suggest working with update panels but if you just need something to happen on the backend without it causing any major change on the web page, I would use jquery and a web service. The main reason for me is that update panels create huge viewstate objects.
Have a look here for asp.net ajax : http://www.asp.net/ajax
And here for an example of jquery and wcf : http://www.codeproject.com/Articles/132809/Calling-WCF-Services-using-jQuery

I have a similar problem. this answer helps me a lot. in your asp button.<asp:button id="button1" runat="server" Text="clickme" OnClientClick="return SomeMethod();" /> and in the SomeMethod which is a js method do your logic like manipulating your page then return false as the mentioned answer suggest.

Related

How can I persist the changes of a text box when it loses focus?

I have several text boxes on a page. I want to save the text in the corresponding TextBox on LostFocus. It is to ensure the data is not lost when power failure or internet connectivity is lost. How can I accomplish something like this?
Another solution would be to use an UpdatePanel. You could then leverage server-side events rather than an event handler. You're markup might look something like this:
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<asp:TextBox ID="SomeTextBox" runat="server" TextChanged="SomeTextBox_TextChanged" AutoPostBack="true" />
</asp:UpdatePanel>
</asp:ScriptManager
and then in the TextChanged handler you could do your work.
Explanation: the TextChanged event will fire on the text box in which the text was actually changed when the post back occurs. The AutoPostBack property is necessary so that the page will in fact post back when the text box loses focus.
One final thing to remember, you will probably need to leverage this.IsPostBack on the page in the Load handler because every time a control is updated it's going to reconstruct the page. It's common that logic in the Load handler only needs to execute one time, but that would pose a problem if you didn't check to see if it was a post back because then it would execute every single time you left a text box.
Use jquery.
First on attach blur event handler, where you call ajax method to server passing new value of the textbox.
Handle this ajax event on serverside and write your data to the database or anywhere else.
Here is a piece of code that may help.
$('#textbox_id').blur(function() {
$.ajax({url:"handler_url.ashx?textbox_value=" + $('#textbox_id').val()});
});
Then create your ashx handler on server and handle your requests with ProcessRequest method. From there you will have access to Request.QueryString where new value of textbox will be stored.

ASP.Net: asynchronous image upload displayed using handler

I have a really specific question for which I don't think I will have an answer but... let's try!
I have an aspx web page that works perfectly with Firefox and Chrome but not on IE9 (don't feed the troll ^^).
My objective is to allow an asynchronous image upload using ASP AjaxControlToolkit (see http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/asyncfileupload/asyncfileupload.aspx for a demo). When the image asynchronous upload is finished, the UploadedComplete function is called and I put the image in a session variable :
if (fileSizeOk && fileTypeOk)
Session["image"] = this.AsyncFileUploadLogo.FileBytes;
In parallel I have a handler responsible for returning an image from the session variable :
byte[] buffer = (byte[])context.Session["image"];
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.OutputStream.Flush();
Then, in my aspx page, I have an asp:Image field in a UpdatePanel that asks to the handler to get the image every five second :
<asp:UpdatePanel ID="UpdatePanelLogo" runat="server">
<ContentTemplate>
<asp:Image ID="ImageFileUploaded" runat="server" ImageUrl="AsyncImageHandler.ashx" />
<asp:Timer ID="TimerFileUploaded" Interval="5000" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
When the user validates the form, I just have to get the variable from the session and I save the image in database with the other values.
Here is my problem: with Firefox and Chrome, the timer provokes the reloading of the image but with IE (even IE9) the image is only displayed after hitting F5. When I put a breakpoint in the handler I can see that it's never called with IE (maybe a caching mechanism?).
Do you have an idea of ​​how to solve this problem?
Thanks for your answers!
Found the solution using a classic Web dirty trick:
this.ImageFileUploaded.ImageUrl = "AsyncImageHandler.ashx?p=" + Environment.TickCount.ToString();
I added that line in the PageLoad(), this last is called on each post back triggered by the timer :)

Button not processing onClick method

I have a button on an ascx control that calls a method on the onClick event:
<asp:Button id="bUpdateText" onClick="FUpdate" ValidationGroup="Update" CausesValidation="False" Text="Update" cssclass="button" runat="server" />
Normally I use this control on it's own page and the button works. This time round however, I am loading this control into a Div that is present on the home page of my site (that way I can show the contents with a little bit of JQuery). However, when I bring the control in this way, the onClick event doesn't fire and I am not sure what could cause that.
Sorry I don't have any code sample but the nature of the site makes it difficult to provide any that would make sense.
In short, what would stop this event firing now?
p.s I have tried adding validation groups to all other buttons and validation controls on the page and there is only ONE form present on the page.
EDIT: I have only just added the validation stuff in to see if that does anything. By default it has been like this and still didn't work:
<asp:Button id="bUpdateText" onClick="FUpdate" Text="Update" cssclass="button" runat="server" />
As mentioned as well, this works when I use this control on it's own page (loaded directly into Default.aspx) so I don't think the case of onClick matters.
EDIT2: I have just noticed that when I click this button, other validation controls on my page are being triggered even though they have their own DIFFERENT validation group?! Taking these controls out doesn't help though.
Thanks.
I have found out what is causing the issue.
This control that I am now including is called on the Page_Finalize() and I am guessing that by this point the viewstate has forgotten it needs to do anything. Loading this control on the page load sorts it out.
Thanks for looking.
To start, if you set the 'causesValidation' property to false, you do not need a validation group.
Additionally, I believe that ASP cares about case when dealing with the OnClick command.
i.e. it should be OnClick not onClick
Yeah, annoying and small, but that might be your problem
You can use Firebug to see what happen in Update validationGroup. it looks like your page execute only client-side button click because of Update validationGroup.

aspx: a form is always forwarded to the same page

on the page products.aspx i created a form:
<form id="send_info_form" method="post" action="send_email.aspx">
<input type="text" name="the_name />
<input type="submit" />
</form>
when i click on submit it's forwarded to the same page (products.aspx) and not to the page i set in action attribute of the form.
It looks like you have a misunderstanding about how ASP.NET's logic works- ASP.NET has a much different paradigm than PHP or ASP does.
It seems like you're taking more of an ASP classic or PHP approach of directly handling the landing pages of forms and POST values, which you no longer have to do. You shouldn't need a separate page to handle the logic of the form submission either; this is all handled by event handlers in the submitting page's codebehind.
Instead of handling input elements directly, you should use ASP.NET's server controls to handle all the inputs for you.
What you should be doing is:
In the Products.aspx page:
E-mail Address: <asp:TextBox runat="server" ID="txtEmail" />
<asp:Button runat="server" ID="btnSubmit" OnClick="btnSubmit_Click" Text="Submit" />
Note that there's no form tag required (besides the one already provided to you when you first make the ASPX page.
Since you're working with an object-oriented language with a business objects representing all of your HTML elements with ASP.NET, you don't have to handle reading from the POST values of the form directly.
In the codebehind for Products.aspx (I'm assuming C#, so Products.aspx.cs), add a method for btnSubmit_Click:
protected void btnSubmit_Click(object sender, EventArgs e) {
string sendEmailTo = txtEmail.Text;
// insert mail sending logic here
}
In ASP.NET, the tag will by default always post itself to the same page. This allows you to handle any events in the codebehind in the ASPX page. It's not clear from your question what exactly you're trying to do. I can think of three possible scenarios:
1) You want to post back to the same page, and toggle visibility of UI elements (other panels, etc.) based on the result of the processing, or redirect the user to a second destination page once processing is complete. This is the most common scenario and the approach I recommend be taken, because it keeps all the logic regarding the processing of the form in one place.
2) You can specify a PostBackUrl to specify another (ASP.NET) page for button controls and whatnot. From there you can do the processing from elements on the first page on the second page using the PreviousPage property. See http://msdn.microsoft.com/en-us/library/ms178139.aspx for more information.
3) If you have a separate page you wish to post to that you don't control that's not ASP.NET-based (i.e., another site's form, or a PHP/ASP3.0 site you run), things get significantly more difficult. ASP.NET puts everything in one giant elements. Since tags cannot reliably be embedded within each other in HTML, you will either have to do a silent POST manually from your codebehind, or use Javascript to quietly submit an ajax request upon submission.

ASP.NET invoke ASP.NET buttons server event in javascript

I am having an ASP.NET page with one Asp.net button control and a normal html link (anchor tage) I want to invoke the postbackl event of asp.net button control when someone clicks on the link.
I used the below code
<a href="javascript:myFunction();" class="checkout" ></a>
<asp:Button ID="btnCheckout" runat="server" Visible="false"
onclick="btnCheckout_Click" />
and in my javascript i have
function myFunction()
{
var strname;
strname = "Test";
__doPostBack('btnCheckout','OnClick');
}
But when runnin gthis , i am getting an error like __doPostBack is undefined
Can any one tell me why it is ?
Thanks in advance
This anyway wouldn't have worked. When you make your .NET control invisible by using 'Visible="false"' it isn't rendered, that means not available at the client.
Back to your question.
1- Where is myFunction defined? Between the tag?
2- Are there more .NET controls on the page? If there aren't any other .NET controls, .NET doesn't add all the scripts that are required for postbacks and stuff.
Why not do the following (based on TheVillageIdiot answer):
<asp:LinkButton ID="lbtnCheckout" runat="server" CausesValidation="false" OnClick="lbtnCheckout_Click" CssClass="checkout" />
With the above example you don't need the fake button and make it invisble. You still can do your postback. Way more cleaner approach I would say.
First of all I tried your code and also not get anything like __doPostBack, then I added another button on the page which was visible but it was all the same. Then I added a LinkButton and got __doPostBack method. You can do post back from javascript but then EventValidation is problem, as it does not allow this kind of thing. I had to use the following to overcome it and it worked:
protected override void Render(HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation(
new PostBackOptions(btnCheckout, "OnClick"));
base.Render(writer);
}
I think I'm bit incoherent in answering so I'll mark it as wiki :)

Resources