Thursday, June 24, 2010

Remove View State for the Asp.net Page

                        This Code Sippnet give you a clean solution on the removal of the view state for  the page and Stored it across in any storage area .By doing like this you can achieve a greater performance on the renderning part  and on the page size.All that we required is to override the LoadPageStateFromPersistenceMedium method on the page .If this is done at the base level of your application then all that we required to inherit from there

protected override object LoadPageStateFromPersistenceMedium()
    {
        try
        {
            return LoadViewState();

        }
        catch
        {
            return base.LoadPageStateFromPersistenceMedium();
        }
    }

The following Sippnet does a saving the view state .Normally it saves to a hidden field inside the page  and once the page is requested it takes from the hidden field and creates the contols and set the state .if we customise here then the state will be saved where ever you want and get the from there on the obove function

    protected override void SavePageStateToPersistenceMedium(object
viewState)
    {
        try
        {
           SaveViewState(viewState);

        }
        catch
        {
            base.SavePageStateToPersistenceMedium(viewState);
        }

    }


    private object LoadViewState()
    {
        if (_formatter == null)
        {
            _formatter = new LosFormatter();
        }
        if (null == Request.Form[VIEW_STATE_FIELD_NAME])
        {
            return null;
        }
        string _viewState =HttpContext.Current.Cache[Request.Form[VIEW_STATE_FIELD_NAME].ToString()].ToString();
        if (_viewState == null)
            return null;
        else
            return _formatter.Deserialize(_viewState);
    }

    private void SaveViewState(object viewState)
    {
        string str = "VIEWSTATE_" + Request.UserHostAddress + "_"
            +Session.SessionID+"_"+ DateTime.Now.Ticks.ToString();
        if (_formatter == null)
        {
            _formatter = new LosFormatter();
        }
        StringBuilder _viewState = new StringBuilder();
        StringWriter _writer = new StringWriter(_viewState);
        _formatter.Serialize(_writer, viewState);
        HttpContext.Current.Cache.Add(str, _viewState.ToString(),null,      
       DateTime.Now.AddMinutes(Session.Timeout), TimeSpan.Zero,
        CacheItemPriority.Default, null);
        RegisterHiddenField(VIEW_STATE_FIELD_NAME, str);
    } 

For serlization for the viewstate we have to use  LOS(Limited Object Serlization ).............

0 comments:

Post a Comment