Wednesday, June 22, 2011

Session and ViewState alternative

Introduction
When you want to remember your data in an ASP.NET site after a postback, you will have to use Session or ViewState to remember your data. It’s a lot work to use Session and ViewStates, I just want to declare variables like in a desktop application.
So I created a library called Merula SmartPages. This library will remember the properties and variables of your page.

Using the code
You can download the SmartPages Library here
Using the SmartPages library is very simple. All that you’ll have to do is create a new ASP.NET page and change the extension of the class from Page to SmartPage.
using System;
using MerulaSmartPages;
namespace SmartPageTester.smartpages
{
    public partial class MyPage : SmartPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
    }
}
In ASP.NET, this won’t work:
using System;
using System.Web.UI;
using MerulaSmartPages;
namespace SmartPageTester.smartpages
{
    public partial class MyPage : Page
    //normal asp.net page (Change Page to SmartPage and it will work!)
    {
        private string value;
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                value = "<h1>Hello world!</h1>"; //set the value
            }
            else
            {
                Response.Write(value); //wont work, value will be empty
            }
        }
    }
}
Read more: Codeproject