Button click triggers full page postback on first click - c#

Despite the fact that I have placed my asp:Button inside an UpdatePanel, it is still triggering a postback on the full page the first time it's clicked. Also, the OnClick event isn't being caught the first time I click the button either, but every single time after that everything works fine.
Any ideas what could be causing this problem? See the code below.
(In my Site.Master file)
<asp:ScriptManager runat="server" AjaxFrameworkMode="Enabled" EnablePartialRendering="true" ValidateRequestMode="Disabled">
</asp:ScriptManager>
(In my actual webpage)
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Editor.aspx.cs" Inherits="Technology.WebForm1"
validateRequest="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<textarea id="htmlTexarea" runat= "server" style="height: 90%"></textarea>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="testBtn" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Button ID="testBtn" style="" runat="server" ClientIDMode="Static" OnClick="testBtn_Click" UseSubmitBehavior="false" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
My C# codebehind is:
protected void Page_Init(object sender, EventArgs e) {
testBtn.Click += testBtn_Click;
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void testBtn_Click(object sender, EventArgs e)
{
String test = "Helloworld";
}
Is there anything I've left out or have done wrong?
EDIT: I added the following to the C# code behind:
protected void Page_Load(object sender, EventArgs e)
{
//Should return POST, returns GET on first click
String test = Request.HttpMethod;
if (!IsPostBack)
{
//stops here first time
String hello = "Hello world";
}
else {
//should stop here
String hello = "Hello world";
}
}
The first time I click the button the server is getting a GET request and IsPostBack is returning false, without changing anything every other click sends a POST request and IsPostBack is true. Anyone know what could be causing this?

The problem was being caused by the fact that I was going from another page to this page using Server.Transfer(...), I'm not entirely sure how but this was affecting the POST request sent by the page the first time but once the page reloaded itself after the request everything worked. In my master page I changed the code to Response.Redirect(...) and it now works perfectly. Apologies if this isn't the clearest explanation but to be perfectly honest I'm not quite sure why this solved the problem, if anyone could clarify what was going on in the comments I'd really appreciate it.

Related

Asp button is called by default postback method

ASPX code :
<asp:Button ID="medicalSub" runat="server" ValidationGroup="medical" Text="Save" CausesValidation="false" UseSubmitBehavior="false" ClientIDMode="Static" OnClick="medicalSub_Click" />
ASPX.CS code :
protected void medicalSub_Click(object sender, EventArgs e)
{
console.writeline("hello");
}
Error
According to that stack trace, the problem is not calling the click method. Instead, it's failing trying to load viewstate for a dropdown list control. This is long before trying to handle any events.
Try this:
copy and paste this in your page load section of your code and check if that helps:
If(!IsPostBack)
{
}
Or the following will hep:
<%# Page so just add the rest => EnableEventValidation="false" %>

UpdatePanel with AsyncPostback tryes to update control outside UpdatePanel

I need to have UpdatePanel with asyncpostback, but in my case it seems that no partial postback happens, but fullpostback. I am new to web forms, please, check the code:
<%# Register TagPrefix="Cust" TagName="CompanyInformationView" Src="~/CustomControls/CompanyInformationView.ascx" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<asp:UpdatePanel runat="server" ID="UpdatePanel1" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" OnClick= "Button1_Click" Text="test" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<Cust:CompanyInformationView ID="CompanyInformationView" runat="server" />
</asp:Content>
So I have Test Button. OnClick it should do "nothing" for test. Also there is custom control on web form. Here is server side code for this form:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// fill in custom control
CompanyInfo c = GetInfo();
CompanyInformationView.Company = c;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var i = 1;
}
CompanyInformationView is custom control with property "Company". There is no ViewState added for this property (so it cannot be loaded properly if postback is done). When I click on Test Button, the page fails, because "CompanyInformationView.Company" is not set (it is not set, because it cannot be loaded from ViewState, I guess).
Instead, I think that it should not work like this. AsynPostback should deal only with UpdatePanel.
Why it wants to reload custom control? Doesn't it mean that Full postback happen or maybe I do not understand Asyncpostback?
PageLoad and all other events are raised on every get\postback, no matter if it's async or full,
In asyncpostback, the response which the server renders includes only the content inside the updatepanel.
Try to Put <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
Before
<asp:UpdatePanel runat="server" ID="UpdatePanel1" ChildrenAsTriggers="true" UpdateMode="Conditional">
Async post back in web forms still proceeds the whole page life cycle as if it's a traditional post. the difference is only the updated content inside target update panel that will be sent in response. so in this case, async post back will still give you exception unless you populate the custom control no matter get/post.
you need to also put the custom control inside another update panel or in the same update panel as the button in order see partial update to happen.

ASP.NET Change label text in custom event

I am trying to change the text on a label from a custom event. When I update the text through a button click event (Button1_Click), everything works. However, when I try to update the same label in a custom event(ArReceiver_OnArDataUpdate) nothing happens. ArReceiver_OnArDataUpdate is getting triggered properly.
Why does my event react differently than a button click event? What do I need to do to get my event working?
This is an out of the box web project in VS2013. Here's the code to explain better:
Code Behind:
namespace WinReceiver
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
ArReceiver.OnArDataUpdate += ArReceiver_OnArDataUpdate;
}
void ArReceiver_OnArDataUpdate(object sender, ArEventArgs e)
{
labelVoltage.Text = "Reset";
UpdatePanel1.Update();
}
protected void Button1_Click(object sender, EventArgs e)
{
labelVoltage.Text = "Button Clicked";
UpdatePanel1.Update();
}
}
}
Default.aspx: (The site.master has the ScriptManager in it by default)
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="labelVoltage" runat="server" Text="..."></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
EDIT:
I did find this question that says it's not possible, but can someone explain why this may not be possible? I'm ok with a page refresh too, but when I tried Respone.Redirect I got exceptions.
If OnArDataUpdate is a static event, it's likely to be fired when the ASP.NET page rendering process is out of scope, and thus the label is not existent because it isn't in scope of the page being processed (since ASP.NET is stateless).
However, if ArReceiver is a control on the page, it should process fine, and the issue could be within the control or something overriding it (depending on when the event fires, it may get overridden by viewstate).

Visual Web Developer html button onclick event didn't fire

Below is my code:
default.aspx:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"
AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="TestAjax._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
//I set an onClick event on this button:
< input type = "button" id="btnCl" onclick = "doJob" />
</asp:Content>
default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
//fires on page load;
}
void doJob()
{
//code here;
}
The question is:
Why didn't the onclick event trigger? (On default.aspx btnCL)
Thanks
You need to use an asp:Button control like this:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
and then have the event method like this:
protected void Button1_Click(object sender, EventArgs e)
{
// your code here
}
When using a regular input tag, onclick is for javascript, you have to instead use the ASP.NET control asp:Button in order to hook up the C# method.
As stated in my comment in OP your current method is making a client-side call (so looking for a JavaScript function called doJob. You need to make a server-side call so need to use an <asp:Button> control. Some example of how you could achieve this:
Web-Page (.aspx)
<asp:Button ID="btnDoJob" Runat="server" Text="Do Job" OnClick="btnDoJob_Click" />
Code-Behind (.CS)
protected void btnDoJob_Click(object sender, EventArgs e)
{
// Do your action here...
}
Because dojob() is a server-side function, but onclick on that input element is a client-side event. You're probably getting an error in your JavaScript console saying that dojob() is an undefined function.
Use an asp:Button instead of an input to make use of server-side click events. Also, dojob() should be protected. By not declaring a protection level I think the default is private so the page controls might not even be able to see it. It should match the event handler for a button click:
protected void dojob(Object sender, EventArgs e)
{
}

Cause an async postback when a listbox is double-clicked

I have an ASP.NET listbox, lstActivities. To edit an item in the list, users can either click lnkButton or double-click on the listbox. I achieve this with:
protected void Page_Load(object sender, EventArgs e) {
if (IsPostBack) return;
var refDblClick = ClientScript.GetPostBackEventReference(lnkButton, "dblClick");
lstActivities.Attributes.Add("ondblclick", refDblClick);
}
protected override void Render(HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation(lnkButton.UniqueID, "dblClick");
base.Render(writer);
}
I would like to change this so that the postback is asynchronous, using AJAX. At the moment, the listbox and button are in an UpdatePanel so there is an async postback when the button is clicked. But when the listbox is double-clicked, a full postback occurs.
<asp:UpdatePanel ID="up" UpdateMode="Conditional" ChildrenAsTriggers="true"
runat="server">
<ContentTemplate>
<asp:ListBox ID="lstActivities" runat="server"></asp:ListBox>
<asp:LinkButton ID="lnkButton" runat="server" OnClick="lnkButton_Click">
Edit</asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
How can I make the double-click refresh only the UpdatePanel?
A few things to try:
<asp:UpdatePanel ID="up" UpdateMode="Conditional" ChildrenAsTriggers="true"
runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lstActivities" />
<asp:AsyncPostBackTrigger ControlID="lnkButton" />
</Triggers>
.........
</asp:UpdatePanel>
or
protected void Page_Load(object sender, EventArgs e) {
if (IsPostBack) return;
var refDblClick = ClientScript.GetPostBackEventReference(lnkButton, "dblClick");
lstActivities.Attributes.Add("ondblclick", refDblClick);
ScriptManager1.RegisterAsyncPostBackControl(lstActivities);
}
I just a ran a quick test with the code you provided and I do get "partial postbacks" (for lack of a better term since updatepanels always do full postbacks) on both, the clicking of the button and the double clicking of the list.
If you set other panels in that page to UpdateMode="Conditional" as you are doing with your UpdatePanel "up", then only elements inside "up" will be updated. If you don't specify the update mode on the other panels, then they will always be updated on postback, because, again, update panels ALWAYS do full postbacks; what they really do is partial refreshes of the page.
Linking MSDN documentation regarding UpdatePanel as I think is a very helpful read.
I tried the solutions suggested, but with no luck. It's quite a complicated page with lots of UpdatePanels so hard to work out the exact problem.
In the end I went for jQuery:
$(document).ready(function () {
$(document).delegate('#ctl00_body_lstActivities', 'dblclick', function () {
eval($('#ctl00_body_lnkButton').attr('href'));
});
});

Categories