I have made a simple project to explain my problem.
This is my Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cusDate"
runat="server"
ValidateEmptyText="true"
OnServerValidate="DateValidate"
ValidationGroup="DateVal"
ControlToValidate="txtDate"
ErrorMessage="Date error"></asp:CustomValidator>
<asp:ImageButton ID="btnSaveDate"
CausesValidation="true"
ValidationGroup="DateVal"
ImageUrl="~/Images/save_32.png"
runat="server" />
</div>
</form>
</body>
</html>
And this is my Default.aspx.cs
using System;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) <<<<<<BREAKPOINT 1 HERE
{
}
}
protected void DateValidate(Object source, ServerValidateEventArgs args)
{
args.IsValid = false; <<<<<<BREAKPOINT 2 HERE
}
}
}
I set two breakpoints, as shown above, and run the application. When I click "btnSaveDate" it first stops at breakpoint 1 and then at breakpoint 2. I thought it would stop at breakpoint 2 first, then reload the page and then stop at breakpoint 1.
Is there something wrong in the code or should it behave like this?
I have read many articles about this and tried a lot of different solutions, but no one has worked so far.
According to the ASP.NET Page Life Cycle, the Postback event handling happens after the Load event.
If the request is a postback, control event handlers are called. After
that, the Validate method of all validator controls is called, which
sets the IsValid property of individual validator controls and of the
page. (There is an exception to this sequence: the handler for the
event that caused validation is called after validation.)
A postback means that a client is making an http request to the server and, every time a request arrives to the server, the Page Life Cycle stages are executed in this exact order. So the second answer is no, is not possible to enter in the breakpoint 2 then before entering the breakpoint 1.
Related
When I change the index in masterpage dropdown list. This is what happens:
1. The current page load event is getting called .
2. Master Page contents gets called and it does not hit (!PostBack) functions which is how it is supposed to be .
3. Selected index changed event is called from where it is redirected to destination Page
4. Destination Page content is getting called.
5. Master Page content is getting called as and this time it hits (!PostBack) functions.due to that my selected value gets reset as I take this value from database and insert first time .
I am confused as to why it is happening, I tried many things but didn't get the result. Also I am not sure whether step 1 and step 2 are also correct process.
I am really struggling with this and need some help.
This is my code
SourcePage.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="PlantOverview.aspx.cs" Inherits="PlantDevelopment.PlantOverview" MasterPageFile="~/Master/MasterPage2.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<meta name="viewport" content="width=device-width, initial-scale=1">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="flex-lg-wrap wrapper">
</div>
</asp:Content>
SourcePage.aspx.cs
using System;
namespace PlantDevelopment
{
public partial class PlantOverview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
}
}
DestinationPage.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Master/MasterPage2.master" AutoEventWireup="true" CodeFile="TestPage.aspx.cs" Inherits="PlantDevelopment.TestPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<!-- Latest compiled JavaScript -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div class="flex-lg-wrap wrapper">
</div>
</asp:Content>
Destinationpage.aspx.cs
using System;
namespace PlantDevelopment
{
public partial class TestPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
}
}
MasterPage.Master
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage2.master.cs" Inherits="Master_MasterPage2" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<nav class="navbar navbar-expand-lg" style="background-color: #081A51; margin-top: 15px;">
<div>
<div class=" justify-content-end">
<div class="btn-group btn-style1">
<asp:DropDownList ID="DD_Line" class="dropDownWindow_master" runat="server" Width="350px" ForeColor="black" Font-Size="22px" AutoPostBack="true" OnSelectedIndexChanged="DD_Line_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="0" Text="Select Line"></asp:ListItem>
<asp:ListItem Value="Line1"></asp:ListItem>
<asp:ListItem Value="Line2"></asp:ListItem>
<asp:ListItem Value="Line3"></asp:ListItem>
</asp:DropDownList>
</div>
</div>
</div>
</nav>
<div class="content" id="pageContent">
<asp:ContentPlaceHolder runat="server" ID="ContentPlaceHolder1"></asp:ContentPlaceHolder>
<div class="footer-wrapper" id="footerWrapper">
</div>
</div>
</form>
</body>
</html>
MasterPage.cs
using System;
using System.Web.UI;
public partial class Master_MasterPage2 : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//blanks dropdown and insert from DB (this is the issue the previous selected value gets reset)
}
}
protected void DD_Line_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("~/Pages/TestPage.aspx", false);
}
}
Ok, we might have to step back a bit more.
When using a master page, and you do a simple navigate to "some" page That page of course is a URL based on the "child" page.
So, when above occurs, then we find:
child page load event fires - (postback = false)
master page load event fire (postback = false).
Ok, at this point in time, then any button click (child page).
then
Child page load event tigger, post-back flag = True
master page load event trigger, post-back flag = True
our button click (or event) in child page runs.
(or event stub in master page runs if event from masterpage)
So, in ALL cases, both child page load, master page load will fire.
However, if we navigate to a new page?
Then we are in effect starting over, and the master page is to be considered a full re-load, and post-back will be false on first page load (after navigate) to the new page. (this holds true for both master + child page).
So, master page does not "only" fire one time on the whole application start, and thus only ever have ONE postback event = false, and then additional post-backs (from master or child) will then of course have post-back = true.
And in fact, page load for master page triggers every time for any event on the current page (just like child page load triggers every time also).
Of course, if we in the child (or master) we re-navigate to the same page using code?
Then again we are starting over.
If you have a button (say in child page) that does some stuff, and THEN navigates to the SAME page, then yes, the master page load event will fire 2 times. (so will the child page load event).
So, a trigger in code such as a response.Redirect() to the same page should be avoided, since it will trigger both load events two times. So, the reason being is that in the current page, if we trigger a button click/event, then both page loads will trigger as always, then the child event code stub runs. But, if for some reason that trigger is a navigate to the SAME page?
Then again we starting over, and both load events will trigger again, - and both master/child will show is-postback = false.
So, a "navigate" to the same page will trigger both on-loads, and both will be postback = false. And this holds true EVEN if we are/were on the SAME current page when that navigation occurs.
And for such navigation to occur on the same page means both load events will have triggered, then your code stub run, and then assuming that stub triggers navigation to the same page, then that will of course cause both post-backs to occur again. (with post-back = false, like we are starting over again). So yes, this is expected, and thus we get 2 page loads for master and child.
From what you suggest/state, the solution would be to remove the current page code that is causing a navigation to the same page. (maybe you test/check the current url then???).
So for any event (in child or master page), then both events trigger (PostBacks = true). However, if you navigate to the same page (as a result of running that event)?
Then if that navigation is the result of code behind in the same page? Well, then yes, we will see/have both load events trigger two times, first time is the "button" or code that we run from that page. (which means postback = true). The 2 load events fire, then we navigate, and if we navigate to the same page, then we are in effect starting over. In such a case, 4 load events will have occurred.
As I stated, the solution is to NOT use code to navigate to the same page we are on, and I see "little" reason for this to occur. About the only time I had code navigate to same page in code behind was some code to re-fresh/re-load the current URL to re-set the page).
I have the following simple aspx code:
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function myFunction() {
document.getElementById("Label1").className = "clientAssignedClass";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label runat="server" Text="Label" ID="Label1"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Update" />
<asp:Button ID="Button2" runat="server" Text="Change at server" OnClick="Button2_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Button ID="Button3" runat="server" Text="Change at client" OnClientClick="myFunction()" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
with the following cs code:
WebForm1.aspx.cs
using System;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.CssClass = "serverAssignedClass";
}
}
}
When I click Change at server (Button2) button and then Update button, the class attribute is retained across postbacks, but when I click Change at client (Button3) and then Update button, the class attribute is not retained across postbacks (after Update postback any changes made at client are lost).
How can I maintain changes made at client (such as a class change made by Bootstrap, i.e. active) across postbacks ?
Well I suppose it is doing what it is designed for. The view state on page is spitted into hidden field named __VIEWSTATE. As it at server side, it cannot take changes done on client side. It is a mechanism to carry back and forth information that you have on server. For more detailed introduction have a look at this article.
Your best bet to take css class set on client side is to put it into some field like hidden field so that it is posted back to server.
ViewState is used to store the state of a page and its controls as set on the server so that state gets preserved between postbacks. It doesn't "know" about changes made to the page on the client.
ASP.NET webforms wants to manage the state of your page its way - everything is done on the server and changes to the state of the page are stored in ViewState.
If you've gotten used to more client-side code, as has become much more common, then working with webforms can be a little bit frustrating for reasons like this. You're trying to maintain your page state on the client, but the page contains server controls that post back to the server. The server then re-renders the page, destroying that client-side state, because it only knows about the state that it maintains.
If possible, your life will be easier if you don't try to mix to two. If you're stuck working on an existing webforms project, try to do everything on the server. If you're creating new content and you want to manage state on the client, avoid using server controls. Just use ASP.NET as an engine to render the initial view.
If you really, really wanted to do this, you could store values in cookies or local storage, and on page load check those values to see if you need to restore some CSS class when the page loads. You could even do something really weird like put details in hidden input, and then on the server side reflect that back somehow so that when the page reloads the client-side script knows what state to (re)set.
I have 5 files.
Default.aspx
Search.ascx
SearchSQL.ascx
Grid.ascx
GridSQL.ascx
I have registered the ascx files in the default.aspx page and use properties to expose the controls to the default page. And that works great.
My issue is how do I send data back and fourth between the different ascx pages? If I register on any of those it will give me a Circular file reference error.
Using public properties, I have the Search.ascx registered on the GridSQL.ascx to pass the search parameters into Gridsql string, and then the GridSQL.ascx on the Grid.ascx file to pass the sql string to the grid databind.
There has got to be a much easier way to pass data BACK & FOURTH between pages, or am I wrong? When you try to register on the other page to pass data back to the page that sent it, you get the circular file reference error. I have heard a few resolutions like changing file structure, which I have tried, and also about Batch, but that kills performance. Believe i have spent days trying to find resolutions on this. I was going to comment on some questions but Stack does not allow me until I have 50 Rep.
My company is requiring us to use all separate files from now on and I just cant believe this is the best way to communicate between user controls.
Proper way is you want to bubble up the child control's event to parent.
Then let parent to forward the event to other controls.
Note: Here is the demo. You might want to rename delegates and methods which make sense to your scenario.
Search (User Control which fires the event)
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="Search.ascx.cs" Inherits="DemoWebForm.Search" %>
<asp:TextBox runat="server" ID="SearchTextBox" />
<asp:Button runat="server" ID="SearchButton"
Text="Search" OnClick="SearchButton_Click" />
public delegate void MessageHandler(string searchText);
public partial class Search : System.Web.UI.UserControl
{
public event MessageHandler SearchText;
protected void SearchButton_Click(object sender, EventArgs e)
{
SearchText(SearchTextBox.Text);
}
}
GridSql (User Control)
Finally, GridSql.ascx receives the search text.
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="GridSql.ascx.cs" Inherits="DemoWebForm.GridSql" %>
<asp:Label runat="server" ID="SearchTextLabel"/>
public partial class GridSql : System.Web.UI.UserControl
{
public void SearchTextMethod(string searchText)
{
SearchTextLabel.Text = searchText;
}
}
Parent
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="Parent.aspx.cs" Inherits="DemoWebForm.Parent" %>
<%# Register src="~/Search.ascx" tagname="Search" tagprefix="uc1" %>
<%# Register src="~/GridSql.ascx" tagname="GridSql" tagprefix="uc2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<uc1:Search ID="Search1" runat="server" />
<uc2:GridSql ID="GridSql1" runat="server" />
</form>
</body>
</html>
public partial class Parent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Search1.SearchText += m => GridSql1.SearchTextMethod(m);
}
}
i would like to create OnClick event for my panel. So far now the most of the google results look more or less like this: adding onclick event to aspnet label. Is there any way, to call codebehind function from javascript or panel attributes? Because I would like to Redirect user to a new page and before that save some information in ViewSTate or Sessionstate. Any suggestions?
In your java script method raise a __dopostback call to a Server side method.
<script type="text/javascript">
function YourFunction()
{
__doPostBack('btnTemp', '')
}
</script>
Where btnTemp is a server side button, so write a onClick event of this button on server side, where you can do the processing and then redirect to other page.
You can have a good understanding of dopostback at DoPostBack Understanding
My aspx page is like:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script type="text/javascript">
function CallMe() { __doPostBack('btnTemp', '') }
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnTemp" runat="server" Text="Test" onclick="btnTemp_Click" />
<div> <asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
</form>
</body>
And my Server Side code is as:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Attributes.Add("onClick", "CallMe();");
}
protected void btnTemp_Click(object sender, EventArgs e)
{
}
Thats the code that I have written, I haven;t included the using statement, Page directive etc in above code.
There is a PostBackUrl property on a ASP.NET Button, you could render the button as normal then postback to a different page - this is where your OnClick method would need to be declared.
I would strongly recommend against posting back to the same page then doing a Response.Redirect(), consider the traffic. The browser requests the page, posts back then is sent a HttpRedirect and then navigates to the new page. With the method I have outlined above this is not required and the browser has to make one request less (meaning the message doesn't have to be sent or the page rebuilt on the server) and is a significant performance benefit.
In a simple ASP page, TextBox AutoPostBack events will prevent Button click events (except where button is tapped very quickly) and AutoPostBack events for other controls (like ListBox).
There's a similar question here, but I wasn't happy with being forced to use client side or AJAX solutions: Have to click button twice in asp.net (after autopostback textbox)
Example ASPX page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="temp.aspx.cs" Inherits="temp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="PostBack"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="PostBack" Text="Button" /><br />
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="PostBack">
<asp:ListItem>value1</asp:ListItem>
<asp:ListItem>value2</asp:ListItem>
</asp:ListBox><br />
<br />
Events Fired:<br />
<asp:TextBox ID="TextBox2" runat="server" Height="159px" TextMode="MultiLine" Width="338px"></asp:TextBox></div>
</form>
</body>
</html>
C# code behind:
public partial class temp : System.Web.UI.Page
{
protected void PostBack(object sender, System.EventArgs e)
{
this.TextBox2.Text += string.Format("PostBack for - {0}\n", ((System.Web.UI.Control)sender).ID);
}
}
I've been able to partially solve this problem for buttons by using mousedown instead of click events to submit the form (I also blocked extra AutoPostBack events client-side and handled any extra field changes during button click events server side)
However, this means my buttons aren't quite behaving in the standard (click on release) way.
Is there a better solution to this problem that doesn't require trying to do everything in javascript client-side? (I'm writing a lot of code that reads server data during these postbacks, so javascript isn't an ideal solution.)
I'm also trying to avoid switching to an AJAX library for these pages since every new library I add has to go through security auditing etc.
Note: I'm currently working with ASP.Net 2.0/VS 2005, but if this type of problem is fixed in a later release that would be a compelling argument to upgrade. (As far as I understand it, the same problem seems to happen in ASP.Net 4/VS 2010)
The reason to set AutoPostBack="true" on a field (or other input control) is because you want the page to postback when that control's data changes - without requiring that the user click a button. It sounds like that is exactly what is happening: when the field loses focus, the page does a postback.
Perhaps I'm misunderstanding the question? Can you provide some more information about how you need the page/form to behave?
Edit: more info, based on comment from OP.
I think I understand: the "normal" case is they select something from a DropDownList1, and you autopostback to set the values of DropDownList2, based on the selected item in DropDownList1. However, the user may not care about the second list; if they click "search", you want the button-click to essentially abort the autopostback (already in progress), and initiate a new postback.
Unfortunately, I don't think there's any functionality in any version of ASP.NET to "abort" a postback already in progress (not from the client-side code, anyway). Therefore, in order to implement the above behavior, you're going to have to do something outside the standard ASP.NET postback behavior. Here's a few ideas, though by no means is it an exhaustive list:
Use AJAX and JS to retrieve the contents of DropDownList2. If the user clicks search while that ajax call is in progress, the page should postback right away.
Store all possible DropDownList2 data in JSON format in your page; use purely client-side JS to populate List2 when List1 changes. Again, if the user clicks "search", the page will postback right away. Depending on how big the pool of possible List2 entries is, this may bloat the page size too much to be workable.
Use client-side JS to disable your search button when List1 changes selection. The user won't be able to click "search" until the autopostback (to fill List2) completes.
Hope this helps!
To make the client side be more interactive and reduce sending all that viewstate and redrawing the page, I add a little jquery into the mix. It makes things like what you are proposing possible. jquery even ships with the asp.net MVC framework so there is no shame in using it with asp.net.
Here is a simple example that uses jquery that demonstrates what I think you want.
First, in the aspx file, add in a reference to the jquery library. I use the
Google content delivery network so you don't even have add this file to your VS project.
Then take the auto postback references out of all your server controls except the button. I left that one to continue doing a postback because I suspect at some point you want a regular post back, all the other controls use ajax to get your server side response.
I started by using your example page with these modifications:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="temp.aspx.cs" Inherits="temp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
// Establish where the output goes.
var outputObject = $("#<%=TextBox2.ClientID %>");
// create a function to do an ajax postback
function doAjaxPostback(sender, value) {
$.ajax({
type: "POST",
url: "temp2.aspx",
data: "id=" + sender.attr("id") + "&value=" + value,
success: function (data) { outputObject.append("<br />" + data) }
});
}
// Use jquery to wire up the event handler. We use the ClientID property in case these
// elements get embeded in some other server control container later.
$("#<%=TextBox1.ClientID %>").keyup(function (event) { doAjaxPostback($(this), $(this).val()); });
$("#<%=TextBox1.ClientID %>").change(function (event) { doAjaxPostback($(this), $(this).val()); });
$("#<%=ListBox1.ClientID %>").change(function (event) { doAjaxPostback($(this), $(this).val()); });
// Use a plain html button tag for ajax only. The server control button gets rendered as
// a submit button which requires it to be handled a little differently.
$("#PlainButton").click(function (event) { doAjaxPostback($(this), $(this).attr("value")); event.preventDefault(); });
});
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="PostBack" Text="Button" /><br />
<button id="PlainButton" value="Plain Old Button">Ajax Only, No postback</button>
<br />
<asp:ListBox ID="ListBox1" runat="server" >
<asp:ListItem>value1</asp:ListItem>
<asp:ListItem>value2</asp:ListItem>
</asp:ListBox>
<br />
<br />
Events Fired:<br />
<asp:TextBox ID="TextBox2" runat="server" Height="159px" TextMode="MultiLine" Width="438px"></asp:TextBox>
</div>
</form>
</body>
</html>
Then for the code behind I just made a tiny change so we can report when we get a regular postback versus the ajax kind:
protected void PostBack(object sender, System.EventArgs e)
{
this.TextBox2.Text += "\n\nGot an asp.net postback\n\n"
+ string.Format("PostBack for - {0}\n", ((System.Web.UI.Control)sender).ID);
}
Okay, so I was trying not to get too fancy but I wanted to demonstrate how easy this is so I made a second page, temp2.aspx but left the aspx file alone as i only needed what is in the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class temp2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = string.Empty;
string value = string.Empty;
Response.Clear();
if (Request.Form == null || Request.Form.Count < 1)
{
Response.Write("I got nothin'");
Response.Flush();
Response.End();
return;
}
id = Request.Form["id"];
value = Request.Form["value"];
Response.Write(string.Format("\nevent from: {0}; value={1}",id,value));
Response.Flush();
Response.End();
}
}
}
Notice that what I did was clear, write, flush and end the response so only the text we want is sent back to the caller. We could have done some fancy stuff in the page_load of the original temp page to check if it is a call from the ajax function that will not clear or flush the response if the incoming Request.Form does not contain a certain field, etc. But by doing it as a separate page, I hoped to simplify the code. This also opens up possibilities.
Say you have a country drop down that has Canada and USA in it and when it changes, you want to sent back data to populate a State/Province dropdown with the appropriate values. By putting the lookup code on its own page the way I did with temp2.aspx, you can then call it from all the pages in your app that have a need for such a service.
Good luck, let me know if you have any trouble understanding my code.