Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

January 2011 - Posts

The ImageMap ASP.Net web server control

In this post I will try to show you how to use the ImageMap web server control. This is going to be a very easy example.

We will write no code but I will use the control to create navigation hotspots.


1) Launch Visual Studio 2010/2005/2008. Express editions will be fine.

2) Create a new asp.net empty web site and call it “NavigationHotspot”.

3) Drag and drop in the default.aspx page a ImageMap web server control from the Toolbox.

4) Let me explain what I did. I have an image that contains two flags. See the image below

 

I want to be able to navigate to two different web pages depending on which part of the image (which flag) the user clicks.

5) Create two web pages. The one is called Nigeria.aspx and the other one Britain.aspx.

6) Inside the form element type 

<asp:ImageMap
 ID="ImageMap1"
 runat="server"
 ImageUrl="~/flags.png"
 Width="300px"
 HotSpotMode="Navigate"
 >
 <asp:RectangleHotSpot Top="0" Bottom="95" Left="0" Right="140" 
 AlternateText="Go to Britain" NavigateUrl="~/britain.aspx" />
 <asp:RectangleHotSpot Top="0" Bottom="95" Left="140" Right="300" 
 AlternateText="Go to Ireland!!!" NavigateUrl="~/Nigeria.aspx" />
 </asp:ImageMap>


The main property to notice here is HotSpotMode="Navigate". Inside our ImageMap control we create 2 RectangleHotSpot and we set the dimensions (Bottom,Left,Right) for each part of the image.Then we set the NavigateUrl property to each page we created.

7) Run your application and click on the different parts of the image and see that you navigate to the appropriate page. 

Hope it helps!!!!

ASP.Net validation controls

In this post I would like to continue talking about validation in ASP.Net applications. I will look into the validation controls that ASP.Net provides. You can have a look at the first post in my blog regarding validation.

You will show you that we can perform all our main validation tasks without almost writing any code. We will add validation to our form by adding one or more controls.We can also display messages to the user.

The controls I am going to look into are:

  • CompareValidator
  • CustomValidator
  • RangeValidator
  • RegularExpressionValidator
  • RequiredFieldValidator
  • ValidationSummary

We need to create the web form first. 

1) Launch Visual Studio 2010/2008/2005 (express editions will work fine). Create a new empty website and choose a suitable name for it. Choose c# as the development language.

2) Add a web form to your website. Leave the default name.

3) Then add a few textboxes in Default.aspx page. Create a table inside the form element and add textboxes for Name,Surname,Age,Email,Website,Password,Confirm Password,Comments.

Add a submit button as well.

The code inside the body element should be like this. if you do not want to type all that, then by all means just copy and paste it.

 

<body>
    <form id="form1" runat="server">
    <div>
    <p>Please note that all fields are mandatory</p>
     <table cellSpacing="2" cellPadding="2" width="400" border="1">
        <tr>
          <td>Name:</td>
          <td>
            <asp:TextBox id="txtName" runat="server"></asp:TextBox>
          </td>
        </tr>
        <tr>
          <td>Surname:</td>
          <td>
            <asp:TextBox id="txtSurname" runat="server"></asp:TextBox>
          </td>
            
        </tr>
        <tr>
          <td>Age:</td>
          <td>
<asp:TextBox id="txtAge" runat="server" Width="70px">
          </asp:TextBox>
          </td>
          
        </tr>
<tr>
          <td>Email:</td>
          <td>
            <asp:TextBox id="txtEmail" runat="server"></asp:TextBox>
          </td>
          
        </tr>

         <tr>
          <td>Web Site:</td>
          <td>
            <asp:TextBox id="txtSite" runat="server"></asp:TextBox>
          </td>
          
        </tr>
        <tr>
          <td>Password:</td>
          <td>
            <asp:TextBox id="txtPassword" TextMode="Password" runat="server">
            </asp:TextBox>           
          </td>            
          
        </tr>
        <tr>
          <td>Re-enter password:</td>
          <td>
<asp:TextBox id="txtconfPassword" runat="server" TextMode="Password">
</asp:TextBox></td>
          
           
        </tr>

          <tr>
          <td>Comments:</td>
          <td>
            <asp:TextBox id="txtcomments" runat="server" TextMode="MultiLine">
           </asp:TextBox></td>
          
            </td>
        </tr>
        <tr>
          <td></td>
          <td>
<asp:Button id="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click">
       </asp:Button>
          </td>
          
        </tr>
      </table>
      
       
    </div>
    </form>
</body>

 

 4) The first requirement one should have when it comes to validating the form is "Not to leave any of the fields empty".

We will use the RequiredFieldValidator from the Validation web server controls in the Toolbox inside Visual Studio.

I will show you the RequiredFieldValidator for the first textbox txtName. It looks like this.

<asp:RequiredFieldValidator 
            ID="NameValidator" runat="server" 
            ErrorMessage="Please enter your name" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtName">
            </asp:RequiredFieldValidator>

 

The most important property is ControlToValidate="txtName" which ties the validation control with our textbox. Run your application and press the submit button. You will see the red "*" appearing.It is so simple.Note that there is no postback in the page.

We have client side validation out of the box.

Go to View->Source of the Html page and have a look at the Javascript generated for you by the runtime.

<script type="text/javascript">
//<![CDATA[
var NameValidator = document.all ? document.all["NameValidator"] : document.getElementById("NameValidator");
NameValidator.controltovalidate = "txtName";
NameValidator.errormessage = "Please enter your name";
NameValidator.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
NameValidator.initialvalue = "";
//]]>
</script>

While you are in the Source of the Html page, have a look on how the validator control renders. The RequiredFieldValidator for the Name field should look something like this.

 <span id="NameValidator" style="color:Red;font-weight:bold;visibility:hidden;">*</span>

 Note that it renders like a span element.

5) I will continue adding RequiredFieldValidator controls for the remaining fields.So the Default.aspx page should look something like this. I am adding only the code in the body element.

<body>
    <form id="form1" runat="server">
    <div>
    <p>Please note that all fields are mandatory</p>
     <table cellSpacing="2" cellPadding="2" width="400" border="1">
        <tr>
          <td>Name:</td>
          <td>
            <asp:TextBox id="txtName" runat="server"></asp:TextBox></td>
        <td>
            <asp:RequiredFieldValidator 
            ID="NameValidator" runat="server" 
            ErrorMessage="Please enter your name" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtName">
            </asp:RequiredFieldValidator>
            </td>
        </tr>

         <tr>
          <td>Surname:</td>
          <td>
            <asp:TextBox id="txtSurname" runat="server">
          </asp:TextBox></td>
              <td>
            <asp:RequiredFieldValidator 
            ID="SurnameValidator" runat="server" 
            ErrorMessage="Please enter your Surname" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtSurname">
            </asp:RequiredFieldValidator>
            </td> 
          
        </tr>
        <tr>
          <td>Age:</td>
          <td>
            <asp:TextBox id="txtAge" runat="server" Width="70px">
            </asp:TextBox></td>
           <td>
            <asp:RequiredFieldValidator 
            ID="AgeValidator" runat="server" 
            ErrorMessage="Please enter your Age" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtAge">
            </asp:RequiredFieldValidator>
            </td> 
        </tr>
        <tr>
          <td>Email:</td>
          <td>
            <asp:TextBox id="txtEmail" runat="server"></asp:TextBox></td>
            <td>
          <asp:RequiredFieldValidator 
            ID="EmailFieldValidator" runat="server" 
            ErrorMessage="Please enter your Email" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtEmail">
            </asp:RequiredFieldValidator>
            </td>
        </tr>

         <tr>
          <td>Web Site:</td>
          <td>
            <asp:TextBox id="txtSite" runat="server"></asp:TextBox></td>
           <td>
          <asp:RequiredFieldValidator 
            ID="SiteValidator" runat="server" 
            ErrorMessage="Please enter your Website URL" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtSite">
            </asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
          <td>Password:</td>
          <td>
            <asp:TextBox id="txtPassword" TextMode="Password" runat="server">
          </asp:TextBox></td>    
           
            <td>
             <asp:RequiredFieldValidator 
            ID="PasswordValidator" runat="server" 
            ErrorMessage="Please enter the password" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtPassword">
            </asp:RequiredFieldValidator>
            
            </td>     
          
        </tr>
        <tr>
          <td>Re-enter password:</td>
          <td>
    <asp:TextBox id="txtconfPassword" runat="server" TextMode="Password">
          </asp:TextBox></td>
          
        </tr>

          <tr>
          <td>Comments:</td>
          <td>
    <asp:TextBox id="txtComments" runat="server" TextMode="MultiLine">
          </asp:TextBox></td>
           <td>
          <asp:RequiredFieldValidator 
            ID="CommentsValidator" runat="server" 
            ErrorMessage="Please enter your Comments" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtComments">
            </asp:RequiredFieldValidator>
            </td>
            
        </tr>
        <tr>
          <td></td>
          <td>
<asp:Button id="btnSubmit" runat="server" Text="Submit" 
onclick="btnSubmit_Click">
</asp:Button></td>
          
        </tr>
      </table>     
    </div>
    </form>
</body>

 

 Run your application and try to submit the form without filling any of the fields.

6) Now I will also add a ValidationSummary control at the bottom of the table element. This is a very nice control that without any configuration connects and displays all the messages that are set in the

ErrorMessage property of all the validation controls.So I am going to add this control after the </table> tag.

 </table>
      
<asp:ValidationSummary ID="ValidationSummary" runat="server"
ShowMessageBox="true" DisplayMode="BulletList" HeaderText="Must be corrected" />
    </div>
    </form>
</body>

Run your application and see all the ErrorMessage values of all the validation controls appearing in the page and in the message box.

That is pretty impressive!!!

7) Now let's add some more validation controls in our form. Let's just say that for the Age field, we need to have a value that is obviously numeric and greater than 18.

We will place a CompareValidator on the form after the Age field. It should be something like this

 <td>
<asp:CompareValidator ID="AgeCompareValidator" runat="server" 
ErrorMessage="Must be greater than 18" ControlToValidate="txtAge" 
Font-Bold="True" Operator="GreaterThanEqual" Type="Integer"
ValueToCompare="18" ForeColor="Red">*</asp:CompareValidator>
</td>

Run your application, type a non-numeric value in the Age field or type a numeric value less than 18. In both cases the form will not validate.

8) Now let's add a new validation control that checks the email is valid. We will use a RegularExpressionValidator validation control.

The code for the email field will look like this

   
<td>
            
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" 
runat="server" ErrorMessage="Email is not valid!!!" 
ControlToValidate="txtEmail" Text="*" Font-Bold="true" ForeColor="Red" 
SetFocusOnError="True"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
            
</td>
      

You will see that we have a ValidationExpression property with a regular expression as a value and I added a new property SetFocusOnError which sets the focus on the control that is invalid.

Run your application and try to fill in the Email field with an invalid email address.The form will not validate.

9) We will add another RegularExpressionValidator validation control that validates the Web Site field.Run your application and try to fill in the Web Site field with an invalid URL.The form will not validate.

10) Now we will add a new field in our form. It will allow the user to enter a date (between 1/1/2011 and 31/12/2011) for a competition. We will add this Competition Date field immediately after Web Site field.

We will use a RangeValidator control.The markup should look like this:

<tr>
 <td>Competition Date:</td>
 <td>
 <asp:TextBox id="txtCompetition" runat="server"></asp:TextBox></td>
 <td>
 <asp:RequiredFieldValidator 
 ID="CompetitionRequiredFieldValidator" runat="server" 
 ErrorMessage="Please enter the Competition Field" 
 Text="*" Font-Bold="True" 
 ForeColor="Red" ControlToValidate="txtCompetition" SetFocusOnError="true">
 </asp:RequiredFieldValidator>
 </td>
 <td>
 <asp:RangeValidator ID="CompetitionRangeValidator" 
 runat="server" 
 ErrorMessage="Invalid Date" ForeColor="Red" Font-Bold="true" Text="*" 
 SetFocusOnError="true" ControlToValidate="txtCompetition" 
 MaximumValue="2011-12-31" MinimumValue="2011-01-01" Type="Date">
</asp:RangeValidator>
            
</td>

</tr>

Run your application and try to fill in the Competition Date field with an invalid date.The form will not validate.

11)  We will add another field in our form. We will call it the UserName field. The user must enter a username. We will use this field to highlight the last validation control, CustomValidator.

 There is a custom validation requirement. The username must be between 6 and 12 characters.

The CustomValidator control allows us to write a method to handle the validation of the value entered. We can write a Javascript validation function to perform validation on the client side and perform validation on the server side by writing code in the code behind file.

So, the markup looks like this.

  <tr>
      <td>UserName:</td>
      <td>
     <asp:TextBox id="txtUsername" runat="server"></asp:TextBox></td>
      <td>
      <asp:RequiredFieldValidator 
      ID="UsernameRequiredFieldValidator" runat="server" 
      ErrorMessage="Please enter your Username" 
      Text="*" Font-Bold="True" 
      ForeColor="Red" ControlToValidate="txtUsername" SetFocusOnError="true">
            </asp:RequiredFieldValidator>
            </td>
            <td>
                <asp:CustomValidator 
                ID="UserNameCustomValidator" 
                runat="server" 
                ErrorMessage="UserName must be between 6 and 12 characters"
                Font-Bold="True"
                ForeColor="Red" 
                Text="*" 
                SetFocusOnError="true"
                ControlToValidate="txtUserName" 
                ClientValidationFunction="CheckUserName" 
                 OnServerValidate="ValidateUserName"
                  ></asp:CustomValidator>
            
            </td>

        </tr>

Note the  ClientValidationFunction="CheckUserName" OnServerValidate="ValidateUserName".

We will have to create a Javascript function CheckUserName and a method in the code behind file called ValidateUserName.

The Javascript function should look like this (place this snippet inside the head element)

<head runat="server">
    <title>Submission Form</title>
    <script type="text/javascript">
    function CheckUserName(source,args)
    {
        var myString = args.Value;

        var length = myString.length;

        if (length < 6 || length > 12)


    args.IsValid=false;
   else
    args.IsValid=true;
   }
</script>  
    
    
</head>

The javascript code above is very easy to understand.I check for the length of the value in the field and I set the IsValid property of the field value to false if the field contains less than 6 or more than 12 characters.

This will trigger the ErrorMessage property of the CustomValidator control and the appropriate message will be printed out in the screen. If this is not the case the validation will pass.

Now we must implement the ValidateUserName routine.In the code behind file you could have something like this.

protected void ValidateUserName(object source,ServerValidateEventArgs e)
    {

        e.IsValid = false;

        try
        {
            string username = e.Value;

            if (username.Length > 6 && username.Length < 12)
                { 

                
                e.IsValid = true;
                 }
        }

        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
       
         
        
    }

The code above is very easy to follow.I check the IsValid property of the Value passed for validation.

The IsValid property gets whether the value specified by the Value property passed validation. If the field value contains less than 6 or more than 12 characters then the ErrorMessage property of the CustomValidator control will be triggered and the appropriate message will be printed out in the screen. If this is not the case the validation will pass.

I want to mention again how important is to have validation on the server.

Run your application and fill in the form correctly. Type less than 6 characters in the username field. You will get a validation error. Now type more than 6 characters in the username field.

The validation will succeed.

12) We want to transfer the form data into another page. Add another page in the web site. Name it Submitted.aspx .

The markup for this page should be like this

<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="lblName" runat="server" Text="Label"></asp:Label>
    <br />

     <asp:Label ID="lblSurname" runat="server" Text="Label"></asp:Label>
    <br />
     <asp:Label ID="lblAge" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="lblEmail" runat="server" Text="Label"></asp:Label>
    <br />

     <asp:Label ID="lblWebsite" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="lblcompetition" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="lblusername" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="lblcomments" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>

 

In the code behind file in the Page_Load event handling routine type

 Response.Write("Thank you for filling in the form.");
            Response.Write("<br/>");

TextBox text1 = this.PreviousPage.FindControl("txtName"as TextBox;
TextBox text2 = this.PreviousPage.FindControl("txtSurname"as TextBox;
TextBox text3 = this.PreviousPage.FindControl("txtAge"as TextBox;
TextBox text4 = this.PreviousPage.FindControl("txtEmail"as TextBox;
TextBox text5 = this.PreviousPage.FindControl("txtSite"as TextBox;
TextBox text6 = this.PreviousPage.FindControl("txtCompetition"as TextBox;
TextBox text7 = this.PreviousPage.FindControl("txtUsername"as TextBox;
TextBox text8 = this.PreviousPage.FindControl("txtComments"as TextBox;
lblName.Text = text1.Text;
lblSurname.Text = text2.Text;
lblAge.Text = text3.Text;
lblEmail.Text = text4.Text;
lblWebsite.Text = text5.Text;
lblcompetition.Text = text6.Text;
lblusername.Text = text7.Text;
lblcomments.Text = text8.Text;

 In the default.aspx page set the PostBackUrl property of the button to the Submitted.aspx.

If you want to learn more about cross page posting have a look at this post of mine.

Run your application, fill in all the form fields correctly and hit the Submit button. You will be transferred to the Submitted.aspx page.

Please note that many controls support validation. Both server controls and HTML controls. DropDownList,ListBox,RadioButtonList can work with validation controls.

HTMLInputText,HTMLTextArea,HTMLSelect,HTMLInputFile controls can work with validation controls.

Another important thing to know is that the validation that takes place on the server side takes place after the Page_Load event being fired.We could have used a different approach to validate the data on the server side.

We could check for valid data in the Page_Load event handling routine.

So if we have this snippet of code

protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            
            if (this.IsValid)
            {
                //more code
            }
        }
    }

 

This will fail. The error will be something like this


"Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.
"

So if we want to check the IsValid property of the Page we must call the Validate() method on the page

if (IsPostBack)
        {
            this.Validate();
            if (this.IsValid)
            {
                
            }
        }

This will not fail. Comment out everything you have in the Page_Load event handling routine.

I understand that this is a very long post. I hope it makes sense. I am sure that if you follow all the steps you will get a good grasp of validation and validation controls.

Drop me an email if you want the source code.

Hope it helps!!!!

A simple example of validation in ASP.Net applications

I am going to start a new series of posts and I am going to cover in depth all the validation mechanisms/techniques/controls we have available in our ASP.Net applications.

As many of you may know, I am a Microsoft Certified Trainer and I will present this series of posts from a trainer's point of view. This series of posts will be helpful to all of novice/intermediate programmers who want to see all the tools available for validating data in ASP.Net applications.

I am not going to try to convince you why we need to validate our data because the reasons for doing so are profound.

So if you do not know much about the subject of validation in ASP.Net applications,  read on. I will be looking forward to your feedback/comments.

I will keep the same format in my posts. I will use hands on examples that everyone can follow.

I am going to cover client-side validation with JavaScript and also cover server side validation. We will also cover validation architecture and validation controls.

Let's see an example of form validation. Every time someone submits data to our server through a web form we must check for various conditions, e.g

  • All fields that are mandatory should be filled
  • Email fields should have appropriate checks
  • Passwords should match
  • Phone numbers should be checked (e.g only numeric data with exactly ten digits)

We will use client side validation and server side validation.You must be careful and do not make the mistake to have only client side validation. You must always validate your data on server side. In fact you should use both client side and server side validation. It is not very difficult to bypass client side validation.

With client side validation we can reduce unnecessary round trips to server. By that we make our application more responsive and the user will get immediate feedback.

We will start with an example of client side validation. It will be very easy and we will just check if some fields are left blank or not.We will start with a simple Html page.

1) Launch Visual Studio 2010/2008/2005 (express editions will work fine). Create a new empty website and choose a suitable name for it. Choose c# as the development language.

2) Add a web form to your website. Leave the default name.

3) Add a html page to your site.I named it Validation.htm. We will add 3 texboxes and a button inside the form element.

4) Inside my body tags I have something like this

 

<body>
<form name="login" method="post" onsubmit="return ValidateForm()">
<table cellspacing="2" cellpadding="2" border="1">
<tr><td align="right"><b>Name:</b></td>
  <td><input id="name" /></td>
  </tr>
<tr><td align="right"><b>E-mail:</b></td>
  <td><input id="email" /></td>
 </tr>
      <tr><td align="right"><b>Age:</b></td>
  <td><input id="age" /></td>
 </tr>
</table>
<input type="submit" value="Click Me!!!" />
</form>

</body> 

5) This is very straight forward. Anyone with basic HTML skills can accomplish that. I am going to add some <span> elements next to each textbox. You will see why I need them later on.

 My code inside the body element looks like this

<body>
<form name="login" method="post" onsubmit="return ValidateForm()">
<table cellspacing="2" cellpadding="2" border="1">
<tr><td align="right"><b>Name:</b></td>
  <td><input id="name" /></td>
  <td><span id="error_name" 
            style="visibility:hidden;color:red">
      Mandatory field</span></td></tr>
<tr><td align="right"><b>E-mail:</b></td>
  <td><input id="email" /></td>
  <td><span id="error_email" 
            style="visibility:hidden;color:red">
      Mandatory field</span></td></tr>
      <tr><td align="right"><b>Age:</b></td>
  <td><input id="age" /></td>
  <td><span id="error_age" 
            style="visibility:hidden;color:red">
      Mandatory field</span></td></tr>
</table>
<input type="submit" value="Click Me!!!" />
</form>

</body>

6) I have a new column added next to each textbox. For the Name textbox I add

<td><span id="error_name" 
            style="visibility:hidden;color:red">
      Mandatory field</span></td>

It is basically a span element with some style that keeps the words "Mandatory field" hidden when the page is loaded.So there will be no error messages when the page is loaded.

7) Inside the head element of the html page we need to add some Javascript code.

 <script type="text/javascript">
        function ValidateForm() {
            var ret = false;
            if (document.all["name"].value == "")
                document.all["error_name"].style.visibility = "visible";
            else if (document.all["email"].value == "")
                document.all["error_email"].style.visibility = "visible";
            else if (document.all["age"].value == "")
                document.all["error_age"].style.visibility = "visible";
            else
                ret = true;
            return ret;
        }
    </script>

 

8) I am not going to go explain in detail what is happening here. If you need to learn JavaScript the best place on the web is W3schools. I have a Javascript function and I check if the fields are empty when the form is submitted. If this is the case for any of the fields a red status with the words "Mandatory field" appears to the user.

9) Run your application and check it out yourself.

10) As it was stated previously we also need to have server side validation.The data is actually used in the server and if errors occur they should be posted back to the user so he can correct them.

11) In your Default.aspx page add 3 label controls and 3 textbox controls. The code inside the body element should be something like this.

 

<body>
    <form id="form1" runat="server">
    <div>
    <table cellSpacing="2" cellPadding="2" width="250" border="2">
        <tr>
          <td>Name:</td>
          <td>
            <asp:TextBox id="txtname" runat="server"></asp:TextBox></td>
          <td>
              <asp:Label ID="lblname" runat="server" ForeColor="Red" />
          </td>
        </tr>        
        <tr>
          <td>Email:</td>
          <td>
            <asp:TextBox id="txtemail" runat="server"></asp:TextBox></td>
          <td>
              <asp:Label ID="lblemail" runat="server" ForeColor="Red" />
          </td>
        </tr>
         <tr>
          <td>Age:</td>
          <td>
            <asp:TextBox id="txtage" runat="server"></asp:TextBox></td>
          <td>
              <asp:Label ID="lblage" runat="server" ForeColor="Red" />
          </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnSub" runat="server" Text="Submit" 
                    />
            </td>
        </tr>
    </table>
    </div>
    </form>
</body>

 

So we have 3 textboxes (Name,Email,Age,) that we want to fill in with data and perform some sort of server side validation. The 3 labels will appear with appropriate instructions if the fields are not filled in with any data.

12) Double click on the button. In the button event handling routine type

 

        if (txtname.Text == "")
            lblname.Text = "Please fill in your name";
        else
            lblname.Text = "";

        if (txtemail.Text == "")
            lblemail.Text = "Please fill in your email";
        else
            lblemail.Text = "";

        if (txtage.Text == "")
            lblage.Text = "Please fill in your age";
        else
            lblage.Text = "";

        if (txtname.Text != "" &&
            txtemail.Text != "" &&
            txtage.Text != "")
        {

            Response.Write("All fields were filled in!!!1");

        }

There is nothing difficult in this code. Some simple IF statements that check the Text properties of the Textboxes and set the Label controls text values accordingly.

13) Run your application. Leave any of the fields empty and hit the button. See the error messages printed out in the screen. Fill in all the fields and check again the message printed out in the screen.

In my next post I will look into ASP.Net Validation framework features. We will see how easy it is to perform validations.

Hope it helps.

Routing in ASP.Net 4.0 Web Forms

In this blog post I would like to talk about a new ASP.Net 4.0 feature, URL Routing. I know this issue has been explained from various people on the web but I will give my own example.

We could implement routing since ASP.Net 3.5 SP1 but it was there primarily to support ASP.Net MVC. Even in that release you could implement rounting in web forms but it was a quite difficult thing to do.

However in ASP.Net 4.0 there is an integrated support for routing. It becomes easy to map requests in your site onto pages in your application.

This is made possible with the introduction of the handler PageRouteHandler that is responsible for dispatching routes onto pages. There is also the MapPageRoute function of the RouteCollection collection that defines a route handled by a page.

Our main goal when designing and implementing web sites is to make them highly discoverable by the search engines. In other words to make them SEO friendly. ASP.Net focuses on SEO and provides us with many SEO oriented features.

Have a look in this post of mine for more SEO features in ASP.Net 4.0.It makes no sense to have an e-commerce website or a website that you place you cv and noone is able to discover this page.

I will demonstrate routing by providing a step by step example using VS 2010 Ultimate edition, C# 4.0 and ASP.Net 4.0.

1) Launch Visual Studio 2010 as Administrator (express edition will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.Choose as Web location ,HTTP and the whole URL should look something like http://localhost/MyRoute

2) Add two web forms to your application. You can leave the first one with the default.aspx name and name the second Products.aspx. Write some sample content on each page e.g "This is the home page", "This is the products page".

3) Build and run your application. You will see the Default.aspx page loading. Then type this in the browser window , http://localhost/MyRoute/Products.aspx and see the Products page loading. Well this is a typical web forms functionality where we basically navigate through to the physical file.

4) Now let's try use routing. Add a new item in your application, a Global Application Class , Global.asax.

5) In the Application_Start event handling routine type:

 void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        
System.Web.Routing.RouteTable.Routes.
MapPageRoute("TheHome""home","~/default.aspx");

System.Web.Routing.RouteTable.Routes.
MapPageRoute("TheProduct""product""~/products.aspx");

    }

6) Now we should make some changes in our web.config file.We must instruct IIS to map all requests through the managed modules that are installed. Open your web.config file and type:

 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      
    </modules>
    
  </system.webServer>

 

7) Run your application again and type

http://localhost/MyRoute/product

http://localhost/MyRoute/home

Congratulations, you have successfully used routing in ASP.Net 4.0.Please note that the original URLs are still valid,

http://localhost/MyRoute/products.aspx

http://localhost/MyRoute/default.aspx

Hope it helps!!!

 

 

More Posts « Previous page