I am currently attempting to find a way for a page to send information on user choices on a page to an HttpModule. For example, if a user either clicked a checkbox or not, the module could log that information for later error checking. My module can log simple data about the page, such as execution time, but I am hoping for more information.
Is such a thing possible? I have tried using Context.Items but have not found any success.
You are probably using bad event in IHttpModule that runs before you set Context.Items item. Try do it in event EndRequest where page was already processed.
In Page:
protected void Unnamed_Click(object sender, EventArgs e)
{
Context.Items["button_clicked"] = "yes";
}
in HttpModule:
public class DefaultHttpApplicationModule
: System.Web.IHttpModule
{
public virtual void Init(HttpApplication context)
{
context.EndRequest += context_EndRequest;
}
void context_EndRequest(object sender, EventArgs e)
{
var app = ((HttpApplication)sender);
var ctx = app.Context;
string clicked = ctx.Items["button_clicked"] as string;
}
}
You can also access the Page instance directly, becasu System.Web.UI.Page is also IHttpHandler.
There are two events HttpApplication.PreRequestHandlerExecute (Before Page events fired) and HttpApplicatoin.PostRequestHandlerExecute (It runs after Page.Unload).
void context_PostRequestHandlerExecute(object sender, EventArgs e)
{
var app = ((HttpApplication)sender);
var ctx = app.Context;
if (app.Context.Handler != null && app.Context.Handler is Page)
{ // Register PreRender handler only on aspx pages.
Page page = (Page)HttpContext.Current.Handler;
}
}
Related
I have two pages MainPage.aspx and ChildPage.aspx. From main page when i click a button i redirect to ChildPage.
If i give the address of ChildPage directly on browser, i do not want to load it directly instead i want to redirect to MainPage.
the ChildPage must be loaded only if it is loaded from the MainPage.
How do I find from where the ChildPage.aspx is loaded. how to find the parent page of it or from where it is loaded.
can we try something in the below code
if (!IsPostBack)
{
if (finding_source)
{
Response.Redirect("MainPage.aspx");
}
}
You can use Request.UrlReferrer.AbsolutePath to see the previous page.
if (!IsPostBack)
{
if (Request.UrlReferrer != null && Request.UrlReferrer.AbsolutePath == "/MainPage")
{
//do what you want
}else{
Response.Redirect("~/MainPage.aspx");
}
}
TIP But be careful with using it with postbacks since it will change the value of Request.UrlReferrer to the current page during a postback.
Even though your question is not clear , here i am trying to give my solution.
MAINPAGE.ASPX BUtton Click
protected void lnkRegister_Click(object sender, EventArgs e)
{
Session["MainPage"] = "true";//Encrypt it if u wish
Response.Redirect("childpage.aspx");
}
CHILDPAGE.ASPX PAGE LOAD
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Session["MainPage"] as string) && Session["MainPage"].Tostring()=="true")
{
//proceed
}
else
{
Response.Redirect("mainpage.aspx");
}
}
GLOBAL.ASAX
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
Session.RemoveAll();
Session.Clear();
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}
it is little difficult to control browser shutdown or close...but you can workaround global asax file when your application shutsdown.
I have a user control loaded by LoadControl, and on the code behind for said user control I try to access a control thats null.
Default.aspx:
protected void Page_Load(object sender, EventArgs e){
// ...
List<String> usersCustomers = custRepo.GetUserCustomers(currentUser.ID).Select(s => s.custName).ToList();
FileTrackingControl fileTrackingControl = (FileTrackingControl)LoadControl(typeof(FileTrackingControl), new object[] { usersCustomers, currentUser });
dashboardWidgetPanel.Controls.Add(fileTrackingControl);
// ...
}
FileTrackingControl.ascx:
public partial class FileTrackingControl : System.Web.UI.UserControl
{
List<string> _custNames;
User _currentUser;
public FileTrackingControl(List<string> custNames, User currentUser)
{
this._custNames = custNames;
this._currentUser = currentUser;
}
protected void Page_OnInit(object sender, EventArgs e)
{
StatToCwData scData = new StatToCwData();
GridView fileTrackingResultsFC = (GridView)FindControl("fileTrackingResults");
// CRASH HERE. NPE: fileTrackingResults is NULL
fileTrackingResults.DataSource = scData.GetControlData(6, _currentUser, _custNames);
fileTrackingResults.DataBind();
}
}
On the basis that you do have a grid view with ID fileTrackingResults (it's always worth double checking!), then I think you're trying to access the controls before they are created (as I recall MS says you shouldn't access the control tree in oninit events). In your case it's probably a case of simply moving the code into the Page_Load event, OR create a Page_PreLoad event and map the event handler manually if you need to reserve the Page_Load for some other sort of functionality. Alternatively, you could create a LoadData type method on your user control and fire it manually (use an interface to declare the method so you can roll it across other code).
Having just added a new button in my web application, I get an error when clicking on it, and I'm wondering if this is related to misplaced code. I will describe what/where I did, briefly. Thanks very much.
In ascx file:
<asp:Button ID="btn_rezerv" runat="server" Text="Reserve film" OnClick="btn_rezerv_Click"/>
In the ascx.cs file:
namespace CinProj.UserControls
{
public partial class FilmsList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();
}
private void PopulateControls()
{
string categId = Request.QueryString["CategID"];
string filmId = Request.QueryString["FilmID"];
....
if (categId != null)
{
.....
}
if (filmId != null)
{
......
Button btn_rezerv = (Button)item.FindControl("btn_rezerv");
}
}
protected void btn_rezerv_Click(object sender, EventArgs e)
{
string fid = Request.QueryString["FilmID"];
ShoppingCartAccess.AddItem(fid);
}
}
}
"Server Error in '/' Application.
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. "
Another problem could be because your PopulateControls method should probably only be called when during the Page Load when it's not a PostBack. I can't tell from above, but to me it looks like it only needs done on Load. Try wrapping that call with this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateControls();
}
}
It's likely the result of making some sort of client change that the server doesn't know about. Many times this is the result of changing values in a dropdown in JavaScript, for example.
To fix, you could:
Do away with using JavaScript for said modification
Use an UpdatePanel and add your control to it. If the client needs to make a change, trigger the UpdatePanel's update in order for the control's viewstate to update.
Suppose there is a user control in a page called Paging.ascx that is embedded in PageWithResults.aspx. This control has the necessary properties to keep track of various details about what page you're on (ie: CurrentPage, TotalRecordsInResults, RecordsPerPage, etc..). It also contains events that fire off when you click on a hyperlink ("next page" or "previous page"). Example below. I need to tell PageWithResults.aspx that one of these LinkButton web controls was clicked. I think I need to assign a delegate in the page, so that when this user control event is called (hyperlink is clicked), it also calls some other method/event in the page class. That way I can quickly check what the new value of CurrentPage is (based on what was called in the event below) and get a new result set for the new page (based on the CurrentPage property). But I'm not sure of the best approach. I'm thinking this will require a delegate, but I'm not sure how to wire it up. If you need more details, please ask.
protected void btnNext_Click(object sender, EventArgs e)
{
this.CurrentPage = this.CurrentPage + 1;
if (OnPageChanged != null) OnPageChanged(this.CurrentPage);
}
I'm thinking I have to put my delegate here somewhere. ??
protected void btnNext_Click(object sender, EventArgs e)
{
this.CurrentPage = this.CurrentPage + 1;
if (OnPageChanged != null) OnPageChanged(this.CurrentPage);
//delegate to call object.method or something
}
Using an event would work fine.
You would create the event within your UserControl like so:
public event EventHandler ButtonClicked;
Then invoke the event when required:
protected void Button1_Click(object sender, EventArgs e)
{
if (ButtonClicked != null)
ButtonClicked(this, new EventArgs());
}
In your page you would need to assign an event handler:
protected void Page_Load(object sender, EventArgs e)
{
UserControl1.ButtonClicked += new EventHandler(UserControl1_ButtonClicked);
}
void UserControl1_ButtonClicked(object sender, EventArgs e)
{
}
As well as using the above approach you can also cast the Page reference in the UserControl and call a public method directly:
MyPage page = (MyPage)Page;
page.AMethod();
Hope this helps.
In my master page, I'm loading a variable in the session like this:
public partial class TheMasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewUserPreferences SessionUserPreferences = new ViewUserPreferences();
SessionUserPreferences = UserPreferences.GetUserPreferencesFromDB(6);
}
}
}
Then, in the code behind of a file, I have this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var test = Session["SessionUserPreferences"];
}
}
But when I debug, test is null. What's causing the problem?
Also, if I put a break point in the master page, it doesn't trigger when I run the aspx page; is this normal?
Thanks.
First thing you are missing the assignment part for UserPreferences.GetUserPreferencesFromDB(6) to the Session object. (I read the comments for #Greg's answer and you mentioned that even after that it is not working.)
Second, Master Page's Page_Load Event is triggered after the Current Page's Page_Load Event, hence the value of Session["SessionUserPreferences"] is null in Current Page's Page Load event since it is not set yet.
Check this link for further information on Page Events:
http://msdn.microsoft.com/en-us/library/dct97kc3.aspx
You have to do Session["SessionUserPreferences"] = something; somewhere before you attempt to retrieve that. Are you setting it somewhere else that you didn't show?