Contents

Tuesday, 3 January 2017


 RequiredFieldValidator Control

RequiredFieldValidator Control is used in an ASP.NET application to validate a particular field is empty or not. For example, you have seen in a registration form user have some of the compulsory field which need to be filled like their name,password,address etc. These field cannot be left empty and if left empty the page generates an error. So in order to generate these kinds of error we can use the validation control named RequiredFieldValidator. It will check for an empty field and if found then it prints an error.

So lets take an example to understand it well. I am going to take the same example of a registration form were we take input for name, blog name and nickname of a particular user. I will set RequiredFieldValidator for name and blog name textboxes and not for nickname as i am assuming that our project is not concerned with nicknames of a user. So after adding these textboxes to our project we also need to add RequiredFieldValidator control for each textboxes that requires validation. All the validation controls can be added just by dragging and dropping these controls for the toolbox under validation.

After adding the required control we also need to change few properties for these. Properties can be set either through the properties window usually found in the right side for the screen or just manually typing the required property to the validation control through the source code. 

After dragging and dropping we will get it as following:

Source View


<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>

After adding few properties for validation:

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ErrorMessage="Name cannot be empty !!" ForeColor="Red" ControlToValidate="TextBox1" ></asp:RequiredFieldValidator>

Properties


ID - ID of the control

runat - As we need to run it on the server

ErrorMessage - It specifies the error which need to be printed when a particular textbox is empty.

ForeColor - This property is added to change the color of the error message.

ControlToValidate - It is added to specify which web control we need to validate(i.e it specifies the ID of the control which needs to be validated. In the above code we are validating TextBox1)

Design View

Output


In the above output you may see that i have not entered the Blog Name so it generated an Error stating that it cannot be blank. Nickname field is not generating an error as we have not set the validation for that texbox.

The best part of these validation controls are it does not allow us to redirect a page to another unless all the validations are satisfied. This is done automatically.


Monday, 2 January 2017


Validations in ASP.NET

Validations are most important part of an ASP.NET project and almost all projects made, make use of these validations. Validations are done to validate a particular input provided by the user before it can be used for a particular operations in our project. 

There are two types of validation :-

1) Client Side 
2) Server Side


Client Side Validation

Client Side Validation dependents on the browser that it is runs(i.e if the browser has disabled it then this technique will not work) and on the scripting language that is used to code it(like javascript, vbscript etc.).


Server Side Validation

Server Side Validation is more reliable as it does not dependent on the browser or any scripting language.

Now lets take about validation controls present in ASP.NET.

There are six types of validation controls in ASP.NET :-

  • RequiredFieldValidator
  • RangeValidator
  • RegularExpressionValidator
  • CompareValidator
  • CustomValidator
  • ValidationSummary
Now we well learn all these in detail in upcoming posts.

Monday, 12 December 2016

Session Managing Technique(Managing State)


2) Application State

Application State variables are created globally for an application. It works across pages and across different sessions. It is like a multi user global data which is created under root directory. It is created explicitly and the name of this special file is Global.asax. It contains many events which are raised at different events of the application.

Events

Application_Start

Application_Start is an event which is called when the application starts.

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup

        }

 Application_End

Application_Error is an event which is called just before the application ends.

        void Application_End(object sender, EventArgs e)
        {
            // Code that runs on application shutdown
        }

 Application_Error

Application_Error is an event which is raised for an unhandled exception which we can handle it
here. 

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

        }

The Global,asax file can be added by right clicking on application name>Add>New Item>Global Application Class.

Global.asax code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace httpstateless
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            Application["User Name"]="Akhil Vijayan";
            Application["Blog Name"] = "ASP.NET Tutorial";
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends.
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer
            // or SQLServer, the event is not raised.


        }

    }
}

In the above Gobal.asax file, we are saving username and blog name in two application object. we now access this in our .aspx page

Application State.aspx Page

Design View



Code View

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace httpstateless
{
    public partial class Application_State : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = Convert.ToString(Application["User Name"]);
            Label2.Text = Convert.ToString(Application["Blog Name"]);
        }
    }
}

You may see that i have converted application variables to string. It is needed because as i said application variables are objects and all the controls in asp.net, hold string values so we need to convert it.

Output



Wednesday, 3 August 2016

Server Side Technique(Managing state)

1) Session State

Session state objects are created when a user request for the ASP.NET when the session state it turned on. Session objects are created different for all the new requests. It can work across all the pages that means we can access the session object in all the pages. This was not possible with viewstate variables.. It is mainly used to store user details like login name. It can also be used to store shopping cart details, customer details etc.

  Session objects consists of session ID's which is uniques for each new requests. Session ID objects are created from HttpSessionState class.

Bydefault, an ASP.NET session state is enabled for all ASP.NET applications. Session variables are called server side technique because they are stored in the web server memory.

In short we can say, session variables are single-user global data stored on the web server which can be accessed across all the web pages.

Let us look at the same example used in viewstate.

Design 

SessionState.aspx page



In this the change i have done is the submit button which will redirect to a new page(i.e. NewPage.aspx). This will help us to show whether it is accessible across all the pages.

NewPage.aspx page



Code Behind

 SessionState.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace httpstateless
{
    public partial class SessionState : System.Web.UI.Page
    {
        string name, blog;
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            name = TextBox1.Text;
            blog = TextBox2.Text;
            TextBox1.Text = "";
            TextBox2.Text = "";
            Session["name"] = name;
            Session["blog"] = blog;
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            TextBox1.Text = Convert.ToString(Session["name"]);
            TextBox2.Text = Convert.ToString(Session["blog"]);
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            Response.Redirect("NewPage.aspx");
        }
    }
}

NewPage.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace httpstateless
{
    public partial class NewPage : System.Web.UI.Page
    {
        string name, blog;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            name = TextBox1.Text;
            blog = TextBox2.Text;
            TextBox1.Text = "";
            TextBox2.Text = "";
            Session["name"] = name;
            Session["blog"] = blog;
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            TextBox1.Text = Convert.ToString(Session["name"]);
            TextBox2.Text = Convert.ToString(Session["blog"]);
        }
    }
}

Output



 After entering the details click on save button to save the content in session state variables. You may use the restore button to check whether it is working fine. After that click on submit button to move to the new page.

In the new page click on restore button to restore the content from the session state variable and it will work fine as session state variables can be accessed across pages.

NewPage.aspx page

After clicking on restore button.






Monday, 18 July 2016


Hidden Field

Hidden Field is another client side state management technique. It is mainly used to store small values. It is not rendered in the browser as it is invisible to the browser. It can hold one value for a variable. 
      To add Hidden Field to the web application we only need to drag and drop the HiddenField component from the ToolBox. Then the source code will have the following code:


  <asp:HiddenField ID="HiddenField1" runat="server" />

This is the way to create a HiddenField. Now we only need to save the value of a variable to this and then access it when required.

Let us look at an example for further clarity.

In this example we just take a TextBox to input the name of the user and two buttons, one for saving the value of the TextBox to the HiddenField and the other button to retrieve the value from it to the TextBox.

Design  


Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace httpstateless
{
    public partial class Hidden : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void Button1_Click(object sender, EventArgs e)    //Save Button Click method
        {
                HiddenField1.Value = TextBox1.Text;      //Saving the TextBox value in the HiddenField
                TextBox1.Text = "";
        }

        protected void Button2_Click(object sender, EventArgs e)   
//Previous Button Click method 
        {
            if (HiddenField1.Value != null)
            {
                TextBox1.Text = HiddenField1.Value;      //Retrieving the value from the HiddenField
            }
        }
    }
} 

Output

 Before clicking save button:



After clicking save button:


After clicking Previous button:


As you can the username is retrieved from the HiddenField.

Point to Remember

  •  It is used for same values.
  • It is not rendered in the browser as it is invisible to the browser.
  • It is preferable when a variable value changes frequently.


Thursday, 7 July 2016



ABOUT ME

I am a Tech Lover. I like to know new tech news and stuffs like that. I am like you all learning and sharing knowledge that i have....

If you like my posts then please like and share and follow me for all the stuffs like these in future.

Thanks for your support. Keep supporting me like this.

Akhil Vijayan

Query String

Query String is used to send data from one page to another page through URL. The Query String are used to start with a "?" sign. If we want to add more Query String we use "&" sign.

Query Strings are mainly used to send small data across pages. In ASP.NET, to move from one page to another we can use Response.Redirect(It is one of the page navigation technique) which redirects the current page to the specified page.Response.Redirect takes URL to specify the path of the new page and with the URL we can pass the Query String and can code to access the value in another page.

I will discuss all the navigation techniques later. Let us stick to the Response.Redirect for now.

Let us take an example to make it clear. We will take the same example which I took for Cookies and ViewState variable. So we will take input name and blog name from the user and will try to move these details to another page and then display it on the new page.

Let us take the name of first page as Page1.aspx and second one as Page2.aspx.

Design

Page1.aspx


Page2.aspx



Code Behind

Page1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace httpstateless
{
    public partial class Page1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Redirecting to Page2.aspx and sending the values with it
            Response.Redirect("Page2.aspx?Name="+TextBox1.Text+"&Blog Name="+TextBox2.Text);
        }
    }
}


Page2.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace httpstateless
{
    public partial class Page2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Accessing the values send by Page1.aspx
            Label1.Text = Request.QueryString["Name"];
            Label2.Text = Request.QueryString["Blog Name"];
        }
    }
}

Output

Output before clicking the redirect button(current page is Page1.aspx):



Output after clicking the redirect button(loads the Page2.aspx):





Now in the above code when we send the data with the URL we first used "?" sign and gave a name to it and then use an "=" sign. After that a "+" sign and pass the TextBox1 value to the name which we used. To pass more value we have to use & and then the name. After sending the data we access it by Request.QueryString in the new page.

Points to Remember

  • It is generally used to send data from one page to another with URL.
  • It is not suitable for storing large data.
  • It is not suitable to send confidential data like passwords as the new page's URL will also contain the text send by us when we redirect to that page(you refer the Page2 output as it reflects the same).