开发者

Why can not make a declaration directly in a page class in case of session variable?

My question is one line yet this is very confusing me. Why i can not declare and initialize a session variable in partial class of a page it throws an error saying

Error 1 Invalid token '[' in class, struct, or interface member declaration E:\ASP.NET\Trial\statemanagement.aspx.cs 17 12 E:\ASP.NET\Trial\

below is the code i tried

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class statemanagement : System.Web.UI.Page
{
    int count=0;
    Session["FirstName"] = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
     if(!IsPostBack)
     {
         count = int.Parse(Session["FirstName"].ToString());
     }
   开发者_JS百科 }
    protected void Button1_Click(object sender, EventArgs e)
    {

        Response.Write(count.ToString());
        Session["FirstName"] =++count;

    }
}

i dont get the error for count variable i dont know why?

Any help will be regarded thanks


That is not a declaration. It is an assignment. You can not place an assignment statement directly inside a class. You have to place it inside a method or property.

Refering to ASP.NET Session State Overview

Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext.Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object.

The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection.

If you like to initialize the session variables independently from the page you can use application event handlers such as Application_Start and Session_Start which you can find in the global.asax file .


You can't do Session["FirstName"] = 0; outside the scope of a method. Try moving it down to be inside Page_Load.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜