ASP.Net 4 Session expires on postback - c#

I'm using ASP.Net 4 (Visual Studio 2010 - C#). My session keeps expiring on postback.
I am setting my session variable in the Page_Init method of the MasterPage. The issue is not a timeout problem.

ASP.NET fails to detect IE10.. please check this..
http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx

looks like issue with post back... how are u doing postback...could you please add details..
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if(Session["abc"] == null)
Session["abc"] = "abcd";
}
}
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
string x = Session["abc"] as string;
Response.Write(x);
}
}

Related

How to set ASP.NET session variable?

I am new to ASP.NET and I am trying to set session variable. I have one form (SelectPlayer.aspx) where I am trying to set the session but when I try to see the result on second page it does not show me any value. Below is my code.
SelectPlayer.aspx
public partial class SelectPlayer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["player1"] == null)
{
lblSelectPlayer.Text = "Select Player 1";
}
}
protected void btnSelect_Click(object sender, EventArgs e)
{
Session["player1"] = "PlayerSession";
Response.Redirect("Score.aspx");
}
}
Score.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (Session["player1"] == null)
{
Response.Redirect("SelectPlayer.aspx");
}
}
Change Response.Redirect("Score.aspx"); to Response.Redirect("Score.aspx", true);
The second parameter of a redirect indicates that you want to end the response. I've found in the past that setting a Session directly before doing a redirect without this second parameter can cause issues.

How can I call a Method of a Content from MasterPage in ASP.NET

I want to call a method of a Content from a master page sending a Parameter to manipulate one label.
public partial class MasterCategoria : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSalada_Click(object sender, ImageClickEventArgs e)
{
produtosCategoria x = new produtosCategoria();
x.changeLabel("Salada");
}
}
Manipulating this button on this WebForm which is a Content
public partial class produtosCategoria : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void changeLabel(string name)
{
lblTexto.Text = name;
}
But this isn't working. How can I do this work?
Thank you guys, and sorry about my english.
The object of type produtosCategoria is already created and it can be accessed from your master page via this.Page.
So to change the label of your content page you can do as in the snippet below.
Also, I added a simple type check so you won't get an error if another content page is loaded
protected void btnSalada_Click(object sender, ImageClickEventArgs e)
{
// Check if it is the correct content page
if (this.Page.GetType() == typeof(produtosCategoria))
{
produtosCategoria x = (produtosCategoria)this.Page;
x.changeLabel("Salada");
}
}
Note: When code executes in the master page this is the master page and this.Page is the content page

Get Public Content Page Variable into Masterpage

I have a public variable in my content page that I need to access in my MasterPage. So I can set a Javascript variable... .
How can I reference a public content page variable from the masterpage?.
I supposed you want to say that you want to access to variable in the MasterPage from Contend Page, if is correct, use this example:
Declare your public or protected variable:
public partial class MasterPage : System.Web.UI.MasterPage
{
public string strEmpresa = "NS";
protected void Page_Load(object sender, EventArgs e)
{
}
}
Set the following directive at the beginning of your content page:
<%# MasterType virtualPath="~/MasterPage.Master"%>
then you can use the public variables of your MasterPage, using Master.NameVariable.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = Master.strEmpresa;
}
}
In other case if you really want access to variable in ContentPage from MasterPage, you just can set the value in Session and then read in MasterPage. For example:
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["myVariable"] != null)
{
TextBox1.Text = Session["myVariable"].ToString();
}
}
}
}
public partial class WebFormMP_TestPublicVariable : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["myVariable"] = "Test";
}
}
}
There are many ways that you can achieve this. check around internet ;).

Preserve value of textbox using View State in Asp.net?

I've a button and a textbox. I want a value to be entered in textbox and when I click on button the page will reload but the value should still be in the textbox. How can I do that. The following code doesn't work
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ViewState["value"] != null)
{
TextBox1.Text = ViewState["value"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["value"] = TextBox1.Text;
Response.Redirect("default.aspx");
}
}
}
Response.Redirect does what it says - redirects the request to a NEW page. ViewState won't get applied, ever. If you need a redirection, consider using session instead.
If you don't need a redirection, simply don't redirect and update only parts of the page that need to be updated.
Viewstate can retain the value only till when you are on the same page. You are redirecting to other page. So instead of using viewstate use session.
asp.net webform have already maintained the viewstate on page refresh . don't need any code for handle this operation .
See this : http://www.w3schools.com/aspnet/showaspx.asp?filename=demo_aspnetviewstate
referred from : http://www.w3schools.com/aspnet/aspnet_viewstate.asp
and see this discussion
try this
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ViewState["value"] != null)
{
TextBox1.Text = Session["value"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["value"] = TextBox1.Text;
Response.Redirect("default.aspx");
}
}
}
Since you are redirecting to a new VIEW so VIEWSTATE will not be of any HELP. SO,Use Session
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["value"] != null)
{
TextBox1.Text = Session["value"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["value"] = TextBox1.Text;
Response.Redirect("default.aspx");
}
}
}

check session in every page?

I am pretty new to .NET - I am making a site that has an admin section that should only be visible to logged in users.
I have created the login code and once a user is authenticated, I then assign them a session variable.
My question is : is there a more efficient way to check the session variable rather than having the following function on each page?
protected void Page_Load(object sender, EventArgs e)
{
checkSession();
}
public void checkSession()
{
if (Session["LoggedIn"] != "true")
{
Response.Redirect("default.aspx");
}
}
thanks kindly!
if you are using a MasterPage you can put the checking code in the MasterPage's Page_Load event if not use either the Global.asax or a custom HttpModule and put the cheking code inside the the AcquireRequestState event handler for the first and the PostRequestHandlerExecute event handler for the second
Exmaple with Global.asax
public class Global : System.Web.HttpApplication
{ ...
void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
// CheckSession() inlined
if (context.Session["LoggedIn"] != "true")
{
context.Response.Redirect("default.aspx");
}
}
...
}
You should probably consider using forms authentication:
http://www.asp.net/web-forms/videos/authentication/using-basic-forms-authentication-in-aspnet
You can configure a page, or folder to always require authorization, so the runtime will take care of that requirement rather than you having to check manually.
You could make your page a class that inherits from a base class that checks for logged in users.
Derive your pages from a custom class that derives from Page
override the Load method by adding your session check code
now all your pages have the validation
public class MyPage : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
{
if (Session["yoursession"] != "true")
{
//code
}
}
public class yourCustomPage1 : MyPage
{
protected void Page_Load(object sender, EventArgs e)
{
//you don't have to check or call any method..
}
}
public class yourCustomPage2 : MyPage
{
protected void Page_Load(object sender, EventArgs e)
{
//you don't have to check or call any method..
}
}
etc...
A good way to start to understand forms authentication in ASP.Net is creating a brand new website.
Go in Visual Studio and create New Project, select Web, then ASP.NET Web Application.
Check it out in Account folder to understand the process and ASP.Net methods.
You can create BasePage and inherit all your page from this base page , set the function in your basepage.
public class BasePage : Page
{
protected void checkSession()
{
if (Session["LoggedIn"] != "true")
{
Response.Redirect("default.aspx");
}
}
}
Your Page
public partial class YourPage : BasePage
{
....
}
Another solution :
In your Http Module, create Principal(Roles) and Identity in order to set authentification and authorization functionnalities, in your http module attach theses informations to current thread.
link : http://msdn.microsoft.com/en-us/library/system.security.principal.iidentity.isauthenticated.aspx
public class BasePage : Page
{
protected void checkSession()
{
if (Session["LoggedIn"] == null)
{
Response.Redirect("~/default.aspx/");
}
}
}
1st Way : Global.asax.cs ADD
void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
Page page = context.Handler as Page;
if ((string)context.Session["LoggedIn"] != "true"
&& !(page.AppRelativeVirtualPath == "~/Default.aspx"))
context.Response.Redirect("default.aspx");
}
2nd Way : You can have the same session management in Master page. Page Load event.
Hope this helps.
You can add this code in the GLOBAL.asax.cs this will check if the session is empty and also it will not redirect if this the request is initialized from the Login page otherwise it will stuck in a loop.
void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
// CheckSession() inlined
if (Context.Request.Url.LocalPath != "/UIComponents/User/Login.aspx")
{
if (context.Session["Name"] == null)
{
FormsAuthentication.RedirectToLoginPage();
}
}
}

Categories

Resources