Mr W
Mr W

Reputation: 676

ASP.Net aspx properties persisted

What would be the best practice to persist property values of an aspx-page?

I have done the following, is there some neater way?

    public string DataTable
    {
        get
        {
            return _DataTable;
        }
        set
        {
            _DataTable = value;
            ViewState["DataTable"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable = Request["dataTable"].ToString();
        }
        else
        {
            DataTable = ViewState["DataTable"].ToString();
        }
    }

Upvotes: 1

Views: 1335

Answers (2)

Radu094
Radu094

Reputation: 28414

You have multiple places where you can persist data,each with it's own pros and cons, and with it' own lifespan:

ViewState - stored individually on each page as a hidden (somewhat encrypted) item on the client. Remember that the data has to make a round trip to the client and back on each postback, so generally it's not a good ideea to store large ammounts of data

HiddenItem - a hidden input control. Works the same as ViewState, except it's not enrypted and you can use the values in the JS from the client

QueryString - same as hiddenitem, but seriously, use it only for small ammounts of data. I think some browsers have a limit on the URL length

Session - has the advantage of being able to store larger ammounts of data, as this is stored on the server end, not on the client. You can get into trouble if the client is using the back/next buttons on the browser, and you need to be carefull about maintaining session data accross server farms(ie. multiple servers running the same webapp)

Cache - almost identical to Session, except you can access it from other sessions. This is better to use for "globally" accesable data (ie. stuff everyone uses in you app)

Static Properties - works the same as cache, but you cannot share it across webfarms, so each member of the webfarm will have it's own static value in it's loaded assembly.

Upvotes: 6

rslite
rslite

Reputation: 84673

I would do it like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            TableName = Request.QueryString["tableName"];
    }

    public string TableName
    {
        get { return ViewState["tableName"] as string; }
        set { ViewState["tableName"] = value; }
    }

I don't like using Request["tableName"] alone since it has to search in more places. Usually I know where I'm sending the parameter.

Also DataTable is a type, so it's best to not use it as a property name.

Upvotes: 1

Related Questions