X



Home>Tutorial>

What is HiddenFields, Advantages and Disadvantages of HiddenFields

Nuelson Penuel Friday, August 28, 2020 ASP.Net

Summary

In this post, am going to teach you what is HiddenFields, advantages and disadvantages of HiddenFields, as well as give examples.

Introduction

ASP.Net web application is developed to run on a standard protocol known as HTTP. In order words, a new instance of a page is created every time when a request is sent to the server to fetch a page. You may also like state management overview, see here; However, after this round trip to the server, the page state will be been lost immediately meaning all instances of created controls will be destroyed and values will be lost. So to overcome this problem, viewstate was introduced so controls state and values can be retained even after a complete round trip to server.

What is ViewState

ViewState is a client side state management technique that can be used for preserving user information within the same page after a round-trip to server.

Advantages of ViewState

1. It very easy to implement 2. It does not require server resources rather it leverage the server 3. View state data can be encoded and compressed

Disadvantages of ViewState

1. Information stored on view state can be seen clearly when the page source is viewed. 2. The page performance become slow if large data is stored on view state 3. View state requires high capacity of memory hence could degrade website performance on mobile phones. 4. View state can only store values for the same page only.

How to Enable and Disable ViewState

At default, asp.net enable view state, however, you can choose to enable or disable view state for single control or for the whole page. To turn off view for a whole page, set at the page directive as below
 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" EnableViewState="false" Debug="true" Trace="true" %>
While to turn view state for a single control, use EnableViewState = "false" property of the control. Example is

<asp:Button ID ="Button1" runat="server" EnableViewState = "false"/>

Securing ViewState Information

Initially, view state data is stored in the form of Base 64 encoding but this encryption seems not to be secured because anyone with high or little skills of decryption can easily break it. However, asp.net provided two other options that can guarantee safety of your data stored in view state. These two options are ViewStateEncryptionMode and EnableViewStateMac. ViewStateEncryptionMode has three different options that can be set: Always: When this property is chosen, every data stored on ViewState will be encrypted always. Auto: Encrypt if a control requests for encryption. For this to happen, the control must call the Page.RegisterRequiresViewStateEncryption() method. Never: Never encrypt the ViewState.

Encrypting ViewState Data Using Message Access Control (MAC)

Generally, the larger MAC key is used to generate a Hash Key. When the key is auto-generated then ASP.NET uses SHA-1 encoding to create a larger key. Those keys must be the same for all the server. If the key is not the same and the page is posted back to a different server than the one that created the page then the ASP.NET Page Framework raises an exception. We can enable it by using.

Preserving Data Using ViewState

In this example, the program will write to get the username and password inputted by the user and preserve it even after a postback. Here is the HTML source of the program
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.vb" Inherits="_Default" EnableViewState="true" Debug="true" Trace="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>ViewState Example</title>
    </head>
    <body>
        <form id="form1" runat="server">
<asp:Label ID="lblstatus" runat="server" Text="" /><br/>
            <div>Username<br/>
                <asp:TextBox ID="txtusername" Text="" runat="server"/><br/>
Password<br/>
                <asp:TextBox ID="txtpassword" Text="" runat="server"/><br/>
 <asp:Button ID="btnsave" runat="server" Text="Save To ViewState" />
<asp:Button ID="btnread" runat="server" Text="Read ViewState" />
            </div>
        </form>
    </body>
</html>
Here is the code behind to write or save to ViewState. When this button is click, the person's username and password will be saved to ViewState. Here is the codebehind for saving to ViewState
Protected Sub btnsave_Click(ByVal sender As Object, ByVal e As EventArgs) 
    If txtusername.Text = String.Empty And txtpassword.Text = String.Empty Then
       ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('Enter username and password');",True)
   Else
      ViewState ("uname") = txtusername.Text

ViewState ("pwd") = txtpassword.Text
End If
End Sub
Here is the code to read information from ViewState.
Protected Sub btnread_Click(ByVal sender As Object, ByVal e As EventArgs) 
    If Not ViewState ("uname") And ViewState("pwd") Then
       
 txtusername.Text = ViewState ("uname")
txtpassword.Text = ViewState ("pwd")

   Else
      
ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('No username and password found');",True)
End If
End Sub

Introduction

Hidden field is one of the most common technique used by web developers to preserve information within a page when the information entered are needed even after postback and do not want that information to be visible to the user. Take for instance, there might be cases where a page on your website requires that users complete a form and after which they have to submit the completed form and is now left for your code to check if all the details are being filled. If all requirements are met then your program take the user to next phase else you display a friendly message that complete missing information. In this case now, you wouldn't want the person to start all over again filling the form, that is where you need state management techniques such as the hidden fields that I have mentioned here now. To learn more about state management, read more on my post about state management here

What is Hidden Field?

Hidden field, as the name implies, is a hidden element placed on html page. This is one of the types of client side state management techniques used for preserving information when a roundtrip is make to the server. You should also know that anyone that knows how to view html source can see HiddenField details. Also, HiddenFields can be easily manipulated by anyone with technical know how because they are not usually encrypted. So, from a security point of view, HiddenFields are not suggested for preserving confidential information. So, don’t store any important or confidential data like password and credit card details with this control.

HiddenField Declaration

 

Advantages of Hiddenfields

1. Hidden fields are supported by all types and versions of broswer 2. HiddenFields seems to be very simple to implement. 3. It does not requires server resources for its implementation

Disadvantages of HiddenFields

1. HiddenFields values are not encrypted hence makes it less effective 2. Storing large data of information on HiddenFields decreases the webpage performance

HiddenFields Events

Just like every other controls, HiddenFields has the following events.
  1. DataBinding: Occurs when Server Control binds to a data source.
  2. Disposed: Occurs when Server Control is released from the memory.
  3. Init: Occurs when Server Control is initialized.
  4. Load: Occurs when server control get loaded on the page. PreRender Occurs before Rendering the page
  5. Unload:
  6. Occurs when Server Control is unloaded from memory. ValueChanged Occurs when the value gets changed between the round-trip (postback).
  7. ValueChanged event is server-side control. This event gets executed when the value of HiddenField gets changed between postback to the Server.

HiddenFields Example

I am going to demonstrate how to use HiddenFields in ASP.Net website to preserve data even after a postback. In this example, am storing two values"username" and "password" So follow these steps carefully. Here is the HTML source for login page
<%@ Page Language="VB" AutoEventWireup="true"  CodeFile="Default.aspx.vb" Inherits="_Default" EnableViewState="false" Debug="true" Trace="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>HiddenFields Example</title>
    </head>
    <body>
        <form id="form1" runat="server">
<asp:Label ID="lblstatus" runat="server" Text="" /><br/>
            <div>Username<br/>
                <asp:TextBox ID="txtusername" Text="" runat="server"/><br/>
Password<br/>
                <asp:TextBox ID="txtpassword" Text="" runat="server"/><br/>
<asp: Button ID="btnsubmit" Text="Submit" runat="server"/>
<asp: Button ID="btnread" Text="Read" runat="server"/>

<asp:HiddenField ID="hfpassword" Value="" runat="server"/> <asp:HiddenField ID="hfusername" Value="" runat="server"/>
            </div>
        </form>
    </body>
</html>
Here is the code to save data to hiddenfield. When the submit button is clicked, the person's username and password will be saved to hiddenfield s.
Protected Sub btnsubmit_Click(ByVal sender As Object, ByVal e As EventArgs) 
    If txtusername.Text = String.Empty And txtpassword.Text = String.Empty Then
       ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('Enter username and password');",True)

   Else

hfusername.Value = txtusername.Text
hfpassword.Value = txtpassword.Text
 
End If
End Sub
Now that we have stored the values, let us retrieve the information when the Read button is clicked.
Protected Sub btnread_Click(ByVal sender As Object, ByVal e As EventArgs) 
    If Not hfusername.Value = String.Empty And hfpassword.Value Then
      lbstatus.Text = "Welcome, here are your saved details"

txtusername.Text = hfusername.Value
txtpassword.Text = hfpassword.Value

Else
 ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('No information saved to HiddenFields');",True)
   
End If
End Sub
That is it. For suggestions, questions let me know on the comment section.

| | Views(693)

See Demo | Download File


Add your comment. Indicate code using code tag


Words: 0 | Chars: 0 | Reading Duration: 0



Images Attachment




Emmason Integratded Services(2017-2024)
All Rights Reserved
Designed and Maintained By Emmason Integrated Services