how to do notification message in ASP.NET Web Forms - asp.net

I have in Site.Master:
<% if(Session["msg"]!=null) Response.Write(Session["msg"].ToString()); %>
I have also on submit form method:
protected void Send_Click(object sender, EventArgs e)
{
Session["msg"] = "Thx for email.";
Response.Redirect("~/Default.aspx");
}
But now when I refresh page or go to another page I still see "Thx for email." but user should see it only once.

You can clear out the Session["msg"] on Page_load (outside of the if(!isPostback))
Or you can create a label on the master page, access that through the child pages to put the message in there, and clear that one on Page load, this gets you away from using Session. Using a Label you can also set the cssClass, allowing bolding, color changes (red for errors, green for success, etc).
If you just want a plan message you could aways go with a literal control, less over head.

This is because Session variable having their value throghout the session.
Session["msg"]
will always have same value on all the pages in a session.
If you want that value should only be used for the page where you redirect then you can use querystring.
protected void Send_Click(object sender, EventArgs e)
{
Session["msg"] = "Thx for email.";
Response.Redirect("~/Default.aspx?msg='true'");
}
then on SiteMaster
<% if(Request.QueryString["msg"]!=null) Response.Write(Session["msg"].ToString()); %>

You have to set Session["msg"] = null after you show the message. Session lives in server at defualt of 20 min. If you do not set it null it will appeear

Try setting the Session["msg"] to null once it is printed on the page.

Related

Asp.net go to previous page

I have 5 dropdownlist in asp.net.User selects 5 dropdownlist after that click to button.Button sends page to another page.If i go previous page dropdownlist selectedvalues and datas lose(it displays default values without selected values)
I tried below
Response.Redirect("PreviousPage.aspx");
datas losing is there any solution ?
Instead of using Response.Redirect(), you can change the PostBackUrl of the button to the target page, or use Server.Transfer(). Once there you should be able to access the properties you need from the Page.PreviousPage object.
Example using Server.Transfer:
Page1.aspx.cs:
protected void SubmitButton_Click(object sender, EventArgs e)
{
Server.Transfer("Page2.aspx");
}
Page2.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
var addressDropdownSelectedValue = ((Page1)Page).PreviousPage.AddressDropdown.SelectedItem.Value; //or SelectedValue
}
With the ScriptManager in the AJAX control toolkit (you get this in 4.0+, I think maybe even in 3.5), you can add history points. You add a history point and use that value to rebuild the page state.
http://msdn.microsoft.com/en-us/library/cc488548%28v=vs.140%29.aspx
You can also strongly type the previous page if you want to grab values from it. You do this with <%# PreviousPage %> directive. Then in code you could use Page.PreviousPage.FindControl

Modalpopupextender with usercontrol

I am using different user controls with Modalpopupextender (within page, repeater etc.) and it took some time to figure all the tricks how to get this two togeather.
I have now ended up with the following problem
When I pass a param into user control
UserControl.ParamID = 1;
I am able to receive it in user control, but at the strange step of page cycle.
When I try to do
protected void Page_PreRender(object sender, EventArgs e)
{
throw new Exception(ParamID);
}
I get null for ParamID!?
But when I do
<% throw new Exception(ParamID); %>
from html, I get a correct ParamID value.
I tryied to store ParamID as ViewState, as a HiddeField, and it is always doing the same error.
Also, when I use this user control wihout mpe, just in regular aspx page, it all works just fine.
What is the catch?

ASP.NET Login Controls, page postback and rendering on logout

I'm a bit puzzled by the behavior of the default ASP.NET Authentication controls, by its lifecycle to be precise.
In my MasterPage, I added a LoginView Control which displays the nice [Login] or [Logout] links. When I am logged in and click on [logout], I set up the control to perform a redirection to the homepage of the application.
Internally, when a click on "logout" happens, a postback is triggered. The following steps happen (among others of course):
The page that fired the postback is reinitialized
The page that fired the postback is reloaded
The LoggingOut event is fired
The LoggedOut event is fired
The page that fired the postback is PreRendered
The redirection happens
The target page is loaded (LoggedOut.aspx in my case)
On most of the pages, this works fine. But some pages expect some data to be initialized for their rendering to happens correctly. When this loggout postback occurs, the data isn't correctly initialized, but the page is still PreRendered which leads to some... "unexpected behavior" >_<
My question is thus twofold:
Why does this rendering step happens since the page won't be displayed at all?
Is there a way to prevent the rendering to happen?
Thanks a lot.
Tim
PS: here's a small VS2010 sample project showing you the call sequence & page lifecycle if you want to try it out for yourself http://dl.dropbox.com/u/11764136/LoginTest.7z
There is a way to prevent the actual rendering of the page.
Stop processing the current request when you redirect the page. This can be done by giving a true parameter to the Response.Redirect method:
Response.Redirect("http://somewhere", true);
You can also do this manually by calling Response.Close();
Are you using if(!isPostBack) test to control what should be rendered/re-initialized and what shouldn't?
Venemo's answer gave me an idea that seems to be working.
Instead of relying on the LoginStatus component to perform the redirection, I registered the MasterPage hosting the LoginStatus components to the LoginStatus.LoggedOut event and fire the redirection "per hand" before the PreRender step can be called.
protected void Page_Load(object sender, EventArgs e)
{
MasterLoginStatus.LoggedOut += new EventHandler(OnUserLoggedOut);
}
private void OnUserLoggedOut(object sender, EventArgs e)
{
Response.Redirect("~/LoggedOut.aspx", true);
}
I was concerned the LoginStatus component might remain dirty by doing this but sofar I haven't found any issue with it e.g. "works until proven otherwise".
Remains the question of "why the component behaves like this" but I guess it was a design decision that will remain unanswered.
Edit: this works fine until you get the same problem for the "login" action. Haven't found a way around this one yet.
I've got a serious problem with a DevExpress control (The report DocumentMap) which sometimes requests the whole report, bypassing the caching mechanism, when the end-user clicks on the logout link on the LoginStatus control. I've tried a lot of approaches to stop dead the "logout" postback so that the report won't get generated (some reports took 5 minutes to render, so the logout action sometimes took that long). I think this is similar to your problem: you don't want to do any heavy processing if the user is logging out. So I've tried a different approach: why didn't I recognize that the postback is indeed a logging out postback? All my pages inherit from a base page, so I've set this code in the base page:
public bool IsLoggingOut { get; private set; }
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
var eventTarget = Request.Params.Get("__EVENTTARGET");
IsLoggingOut = eventTarget != null && eventTarget.Contains("HeadLoginView$HeadLoginStatus");
}
Now all I need to do in my page is to surround any heavy processing with a test of !IsLoggingOut... You could even do you redirect to the LoggedOut page without having to handle any events, just like this:
protected override void OnLoad(EventArgs e)
{
if (IsLoggingOut)
Response.Redirect("~/LoggedOut.aspx", true);
}
Even if you prefer to use the event handler to do that redirect, being able to know that the postback is indeed due to a logout click is a nice thing!
In my case, I was having this problem with the LoginStatus control. I can't see why it is a useful design to post back and Render the page when the user has clicked "logout". Through some tests, I found that I had to let the page go through its entire lifecycle, so Reponse.End() and Response.Transfer() did not work.
My solution was to add event handlers for the LoginStatus LoggedOut event, and then override the Render() method in the master page to do nothing if the user has logged out. I actually had the LoginStatus nested inside a user control that was then in the master page, so I had to bubble the event.
In my user control containing the LoginStatus control, I added an event handler for the LoggedOut event. In the UserStatus.aspx file:
<asp:LoginStatus runat="server" ID="loginStatusDefault" OnLoggedOut="loginStatusDefault_LoggedOut" ... />
Then in the code-behind:
public event EventHandler LoggedOut;
protected void loginStatusDefault_LoggedOut(object sender, EventArgs e)
{
if (this.LoggedOut != null)
this.LoggedOut(sender, e);
}
Now in the master page default.master, I have already included the UserStatus control:
<c:userstatus ID="ctlUserStatus" runat="server" />
and in the code-behind:
protected void Page_Init(object sender, EventArgs e)
{
ctlUserStatus.LoggedOut += ctlUserStatus_LoggedOut;
...
}
bool IsLoggedOut { get; set; }
void ctlUserStatus_LoggedOut(object sender, EventArgs e)
{
IsLoggedOut = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (!IsLoggedOut)
base.Render(writer);
}
For me, the page rendering is what was bombing out when the user clicked "logout", so this took care of the problem for all pages.
What I did was have the logout link or onloggingout control just redirect to another page, "Logout.aspx" which then handles the log out code. Works great actually.
protected void LoginStatus1_LoggingOut(object sender, EventArgs e)
{
Response.Redirect("~/Logout.aspx");
}

ASP.Net Page Not Posting Back - Reloading Instead

I have a simple ASP.Net login page. When the login button is clicked, the page should post back and the even should be handled by my server-side event handler. Instead, the page simply reloads. Page.IsPostBack is false.
I've put breakpoints in the Page_Load/Init (where applicable) handlers of the Master page, the ASPX page and the UserControl (ascx). When I hit the Login button, instead of getting a post back and having my event handler called, I simply get the page load as if it was a fresh request.
But that's not the end of it! The login page takes a single query string parameter: Login.aspx?id=123456. The above failure occurs when using this parameter. However, if I enable URL Rewriting in order to make the query Login/123456, the error does not occur; I get a post back and my event handler is called in this instance.
So why am I not getting the expected behaviour from my page? What about the rewritten URL is making the problem go away?
Login Button is declared in LoginUserControl.ascx:
<asp:Button ID="SubmitLinkButton" runat="server" Text='Log In' OnClick="SubmitLinkButton_Click"></asp:Button>
And the handler in the code behind:
protected void SubmitLinkButton_Click(object sender, EventArgs e)
{
Authenticate();
}
SubmitLinkButton_Click is never called. :(
Edit (more code):
//Page_Init on the Master page
protected void Page_Init(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
try
{
if (SessionFacade.User != null)
{
loginlabel.Text = "Logged in |";
LoginLink.Visible = true;
}
}
catch
{
FormsAuthentication.SignOut();
CacheFacade.RemoveSessionValues();
Session.Abandon();
Session.RemoveAll();
HttpContext.Current.Response.Redirect("~/Login.aspx");
}
}
else
{
loginlabel.Text = "";
LoginLink.Visible = false;
}
}
Page_Load on the ASPX page:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack.Equals(false))
{
/* Some business stuff that boils down to this: */
Session["company"] = Request["company"];
}
}
Page_Load on the Login Control:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//honestly, there's no code here
}
}
P.S: I need to keep the non-url-rewrite way of accessing the login page, because many users are still navigating to that URL.
P.P.S: Even if URL rewriting isn't enabled, the error still occurs.
Whenever I've seen this problem in the past it has usually been attributed to URL re-writing. I would usually reach for Fiddler to trace the HTTP activity. My hunch tells me after you click the button and see the POST request it will quickly be followed up by a 302 redirect to the login page.
You note that "The above failure occurs when using this parameter" of the login.aspx page. Are you certain there is no url-rewriter configuration that for example, may strip out any querystring values and do a redirect?
Try to check your caching policy. Possibly your request is cached
I cleared the history on my IE browser and the problem went away.
Did you try to use a different browser? Once I had a similar problem, and it solved by re-installing Firefox!

ASP.net control Postback Problem (Can't read the value the user entered!)

I've written a custom widget to allow a user to select a location from a database of locations. This is my first ASP.net custom control. It seemed like everything was working fine, but now there's a problem.
My control implements the RaisePostBackEvent function as follows:
public void RaisePostBackEvent(string eventArgument)
{
SelectedLocationId = eventArgument.Split('|')[0];
SelectedLocationDescription = eventArgument.Split('|')[1];
}
I wrote a test page and included the following in my ASP code:
<%= locationSelector.SelectedLocationId %>
That worked fine.
However, in my web application, the following code does not work:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
Response.Write(locationSelector.SelectedLocationId);
// SelectedLocationId is null here!!!
}
When I run this code in the debugger, I see that my Page Load event fires before the Post Back event! Therefore, the data is not yet read from the postback. I know that using the MS provided text field control, the text is available at Page Load, so I think I must be doing something wrong.
How can I read the location that the user selected when the Page Load event fires? To clarify, I'm refering to the Page Load of a web application page.
You're setting SelectedLocationId on a postback event and at the same time you are trying to retrieve its value on the first load. SelectedLocationId will be null all right.
Try:
protected void Page_Load(object sender, EventArgs e)
{
if (locationSelector != null)
Response.Write(locationSelector.SelectedLocationId);
}

Resources