>
 



ViewState is the built-in structure for automatically retaining values between multiple requests for the same page in ASP.NET. In other words, ViewState technology saves/restores page state between postbacks. On the other hand, this technology comes with an overhead that affects performance especially during page load since the state data is maintained in a hidden field.

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJLTMzMTY4NDI5ZGRrYY+UdQNeb33gRiGcw2LoiMHduA==" />

Reducing ViewState Size

We can completely disable viewstate by setting EnableViewState to false in the page directive but you need extra programming effort for you to take care of the page state. It is a good idea to disable ViewState for the controls that do not actually need it such as Literals and Labels by setting EnableViewState to false. But this do not entirely solve the problem. 

Compressing ViewState

ASP.NET 2.0 comes with the System.IO.Compression namespace, which contains classes with functionality to compress/decompress streams. In ASP.NET 1.1, developers must use third party compression tools such as ICSharpCode.SharpZipLib to compress viewstate.

Compressing/Decompressing using GZipStream

The following class contains two methods for compressing and decompressing a stream.  

using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.IO.Compression;

public static class CompressViewState
{
    public static byte[] Compress(byte[] data)
    {
        MemoryStream output = new MemoryStream();
        GZipStream gzip = new GZipStream(output,
                          CompressionMode.Compress, true);
        gzip.Write(data, 0, data.Length);
        gzip.Close();
        return output.ToArray();
    }

    public static byte[] Decompress(byte[] data)
    {
        MemoryStream input = new MemoryStream();
        input.Write(data, 0, data.Length);
        input.Position = 0;
        GZipStream gzip = new GZipStream(input,
                          CompressionMode.Decompress, true);
        MemoryStream output = new MemoryStream();
        byte[] buff = new byte[64];
        int read = -1;
        read = gzip.Read(buff, 0, buff.Length);
        while (read > 0)
        {
            output.Write(buff, 0, read);
            read = gzip.Read(buff, 0, buff.Length);
        }
        gzip.Close();
        return output.ToArray();
    }

You need to save this class in a .cs file in the App_Code directory.

Utilizing the CompressViewState Class

In order to compress the ViewState of a web page, you have to override the two methods LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium.

The folowing code creates a BasePage class which inherits from System.Web.UI.Page, and web pages using the following Base Page class as the base class utilizes ViewState compression. The BasePage class adds an additional hidden field __COMPRESSEDVIEWSTATE, to store the compressed ViewState.

using System;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
using System.Configuration;
using System.Threading;
using System.Globalization;
using System.Text;

public abstract class BasePage : System.Web.UI.Page
{
    private ObjectStateFormatter _formatter =
        new ObjectStateFormatter();

    protected override void
        SavePageStateToPersistenceMedium(object viewState)
    {
        MemoryStream ms = new MemoryStream();
        _formatter.Serialize(ms, viewState);
        byte[] viewStateArray = ms.ToArray();
        ClientScript.RegisterHiddenField("__COMPRESSEDVIEWSTATE",
            Convert.ToBase64String(
            CompressViewState.Compress(viewStateArray)));
    }
    protected override object
        LoadPageStateFromPersistenceMedium()
    {
        string vsString = Request.Form["__COMPRESSEDVIEWSTATE"];
        byte[] bytes = Convert.FromBase64String(vsString);
        bytes = CompressViewState.Decompress(bytes);
        return _formatter.Deserialize(
            Convert.ToBase64String(bytes));
    }
}

Demo

Demo project contains two web pages. You may compare the compression performance using the demo project.

 

An online demo web page without viewstate compression.
An online demo web page with viewstate compression.

If you view the HTML of the page with viewstate compression, the __VIEWSTATE field is empty, while our __COMPRESSEDVIEWSTATE field contains the compressed ViewState, encoded in Base64.

ViewState Compression Performance

After few tests using the demo project, ViewState size is reduces by 40 - 60% resulting shorter response times for users and less bandwidth need for site owners.

Compression, decompressing, encoding and decoding data is a quite heavy work for the server so while you are saving from bandwidth and offering shorter response times for users, you are having a performance hit on the server's hardware.

Currently rated 5.0 by 5 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5



If you try to use Enter key in ASP.NET, according to your browser type, you can get really weird results. In my previous article Default Button in ASP.NET 1.1, I described two methods to make enter key default button for form inputs in ASP.NET 1.1.

Fortunately, ASP.NET 2.0 makes this easier by introducing a concept of "default button" that can be used with either a <form> or <asp:panel> control. What button will be "clicked" depends of where acutally cursor is and what button is choosen as a default button for form or a panel.

For example, with the below sample:

<html>
<body>
   <form defaultbutton=“button1” runat=“server”>
      <asp:button id=“button1” text=“btn1” runat=“server”/>
         <asp:panel defaultbutton=“button2” runat=“server”>
            <asp:textbox id=“textbox1” runat=“server”/>
            <asp:button id=“button2”  text="btn2" runat=“server”/>
          </asp:panel>
    </form>
</body>
</html>

If the enter key is selected the first time the page is loaded, "button1" will be the button that receives the post-back event. If the enter key is hit while the user has their cursor focus within the "textbox1" textbox (contained within the <asp:panel>), then "button2" will be the button that receives the post-back event. 

Currently rated 3.5 by 4 people

  • Currently 3.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5



Hitting the enter key in a TextBox may sometimes cause undesired effects in ASP.NET 1.1. For example, the wrong submit button's click event may be triggered or no click event of any button is triggered.

Suppose that, you have one ASP.NET textbox and a button in a web form and OnClick event of the button contains the following code:

Response.Write("Clicked");

If you press the enter key when the textbox has focus, the form will be submitted but button's click event will not be executed.

Place an HTML textbox into the form (it may be invisible):

<INPUT type="text" style="visibility:hidden"/>

If you press the enter key when the textbox has focus, form will submit and the button's click event will be executed.

If you have a single button in a form, the solution described above may be useful. However, for forms with more than one button, we need to specify exactly what button will be clicked when visitor presses the enter key.

Solution 1: Using a Custom Javascript Function


The method below describes the way to specify a default button to submit when the user hits the enter key in a textbox.

<script language="JavaScript">

function clickButton(e, buttonid)
{
      var evt = e ? e : window.event;
      var bt = document.getElementById(buttonid);
      
      if (bt)
      {
          if (evt.keyCode == 13)
          {
               bt.click(); 
               return false;
          }
     }
}
</script>

When you press a key, OnKeyPress event is fired on the client side. This calls a function (clickButton) to which we pass the default button's id. The function simulates a mouse click on the button.

In order to associate above JavaScript function with the textbox, place the following snippet to the code behind.

TextBox1.Attributes.Add("OnKeyPress", "return clickButton(event,'" + Button1.ClickID + "')");

The above code snippet generates the following HTML code:

<input name="TextBox1" type="text" id="TextBox1" onkeypress="return clickButton(event,'Button1')"  />

This causes Button1 to be clicked when the enter key is hit inside Textbox1.

Solution 2: Using the Built-in Javascript Function


You have to place the clickButton JavaScript function in every web page for the method described in Solution 1 to work.

Place the following snippet to the code behind:

TextBox1.Attributes.Add("OnKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + Button1.UniqueID + "','')");

The code snippet given above, renders an extra attribute for Textbox1 that checks for a key press and if it's the enter key, it fires ASP.NET's __doPostBack method with the unique id of the default button that virtually presses it.

Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5



The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on <body> tag of your page.

<body OnKeyPress="return disableKeyPress(event)">

The javascript code should be:

<script language="JavaScript">

function disableEnterKey(e)
{
     var key;     
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox     

     return (key != 13);
}

</script>

If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:

<input type=”text” name=”txtInput” onKeyPress=”return disableEnterKey(event)”>

Currently rated 4.1 by 10 people

  • Currently 4.1/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5



.Net provides several different ways to extract integers from strings. In this article, I will present the differences between Parse, TryParse and ConvertTo.

Parse: This function takes a string and tries to extract an integer from it and returns the integer. If the string is not a numerical value, the method throws FormatException. If the extracted number is too big, it throws OverflowException. Finally, if the string value is null, it throws ArgumentNullException.

Int32 intValue = Int32.Parse(str);

Convert: This function checks for a null value and if the value is null, it returns 0 instead of throwing an exception. If the string is not a numerical value, the method throws FormatException. If the extracted number is too big, it throws OverflowException

Int32 intValue = Convert.ToInt32(str);

TryParse: This function is new in .Net 2.0. Since exception handling is very slow, TryParse function returns a boolean indicating if it was able to successfully parse a number instead of throwing an exception. Therefore, you have to pass into TryParse both the string to be parsed and an out parameter to fill in. Using the TryParse static method, you can avoid the exception and ambiguous result when the string is null.

bool isParsed = Int32.TryParse(str, out intValue);

Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5