-2-

 

Server Controls

 

In this chapter, we will use the controls freely available with IIS to build a real life application in ASP+. Once you get familiar with the workings of these controls, we will then show you how you can build a similar control yourself. So get hooked on to your computer and start on.

 

The file a.aspx, sent by the server, will display a textbox and a button in the browser window.

 

a.aspx

<%@ language=C# %>

<form action="a1.aspx" >

<asp:textbox id="aa" runat="server"/>

<asp:button text="Click a.aspx" runat="server" />

</form>

 

a1.aspx

<%@ language=C# %>

<form action="a1.aspx" >

Name: <asp:textbox id="aa" runat="server"/>

<asp:button text="Click a1.aspx" runat="server"/>

</form>

 

 

You may be tempted to ask as to what is so unique about a textbox and a button.

 

To begin with, we have not used any HTML tags to generate these two controls. A special tag asp:textbox has been implemented, using two attributes called id and runat. In a similar manner, a tag called asp:button, having the attributes text and runat, has been employed for the button. This ASP.Net directive asks the server to generate the HTML tags for the corresponding user interface widgets, at the server end with the specified attributes. The View-Source menuoption displays the following in respect of a.aspx:

 

View-Source

<form action="a1.aspx" >

<input name="aa" type="text" id="aa" />

<input type="submit" name="ctrl2" value="Click a.aspx" />

</form>

 

When these special ASP.Net tags are converted into input tags in the HTML file, the attribute runat is discarded. Further, the button is not assigned any name in the aspx file, due to the missing id attribute. Therefore, the server names it ctrl2. The View-Source confirms that the aspx file now resembles an HTML file.

 

After the text vijay12 is entered in the textbox and the submit button is clicked, the IE requests for the file a1.aspx and the address bar changes to:

 

http://localhost/a1.aspx?aa=vijay12&ctrl2=Click+a.aspx

 

But to our astonishment, the textbox is blank despite the fact that we entered the word vijay12 in it. All the details that were entered in the earlier browser windows too are nowhere to be seen. The View-Source displays the same contents as before.

 

View-Source

<form action="a1.aspx" >

Name: <input name="aa" type="text" id="aa" />

<input type="submit" name="ctrl2" value="Click a1.aspx" />

</form>

 

When we click on the button after writing 'no', the address bar changes to- http://localhost/a1.aspx?aa=no&ctrl2=Click+a1.aspx

but the output displayed by View-Source remains the same.

 

View-Source

<form action="a1.aspx" >

Name: <input name="aa" type="text" id="aa" />

<input type="submit" name="ctrl2" value="Click a1.aspx" />

</form>

 

This erratic behavior is the outcome of initializing the action form with the name a1.aspx, which is also the name of the file in which it is contained. The server discards any data that is typed in. Hence, the fields are initialized to default blank values.

 

Take a situation where we have a large form with numerous fields. You may enter all the data correctly, barring one, where you may have committed some error. In consonance with the behavior illustrated above, all the fields will be returned empty. They will have to be retyped, thereby compelling us to be cautious in future while entering data. This is the penalty that we get, for being inattentive while entering data.

 

A better way out would be to redisplay the form with all the fields that have correct entries in one colour, and the field having the incorrect entry in a different colour. This would obviate the need to re-enter a large amount of data.

 

Let us see how the server can be solicited to retain information that has been typed in.

 

a.aspx

<%@ language=C# %>

<form action=”a.aspx” runat="server">

<asp:textbox id="aa" runat="server"/>

<asp:button text="Click a.aspx" runat="server" />

</form>

 

The only modification made by us in the source code has been, the addition of the attribute runat to the form tag in the file a.aspx. Also, the action attribute is initialized to the same file. After the addition of this attribute, the View-Source now displays a file that is vastly at variance from the earlier one.

 

View-Source

<form name="ctrl0" method="post" action="a.aspx" id="ctrl0">

<input type="hidden" name="__VIEWSTATE" value="dDwxNDgwNTg2MzM2Ozs+" />

 

<input name="aa" type="text" id="aa" />

<input type="submit" name="ctrl1" value="Click a.aspx" />

</form>

 

A field called __VIEWSTATE has been created, which is of the type hidden. A hidden field does not show up in the browser window, but its value is sent across to the server. We shall explain this concept with a simple HTML example.

 

a.html

<form action=a1.html>

<input type=hidden value=hell name=aa>

<input type=submit value=click>

</form>

 

We have a hidden field aa whose value is 'hell'. While displaying this file, only the submit button labeled 'click' is displayed. The hidden field remains invisible in the browser window. However, when the submit button is clicked, the URL that is generated, shows this field as well as its value, as:   http://localhost/a1.html?aa=hell

 

In a.aspx, the value of the hidden field is a long and cryptic number. The form is assigned a name and an id, both initialized to ctrl0. The method attribute is given a value of post. We shall explain this concept later. By default, the method attribute has a value of 'get'. In the textbox, we enter 'vijay13' and then click on the button. The page is refreshed and the URL bar shows http://localhost/a.aspx

As the method is 'post', the parameters are not displayed in the URL, as was done earlier. 'Post' does not send the parameter values along with the URL, whereas, the 'get' method does so. In the case of 'post', they are transferred as a separate packet with data. As far as the ASP.Net page is concerned, the task of fetching the parameter values remains the same.

With the new contents in the HTML file, the data that is entered most recently, is recovered. Thus, the textbox shows 'vijay13'.

 

Let us now look 'behind the scenes' to figure out why this happens.

 

View-Source

<form name="ctrl0" method="post" action="a.aspx" id="ctrl0">

<input type="hidden" name="__VIEWSTATE" value="dDwxNDgwNTg2MzM2Ozs+" />

 

<input name="aa" type="text" value="vijay13" id="aa" />

<input type="submit" name="ctrl1" value="Click a.aspx" />

</form>

 

This time, the textbox's value field displays the word 'vijay13'. This could have been possible only if the Web Server remembered what was transferred. Hence, in the return round trip from the server to the browser, it adds the value attribute to the textbox and assigns the new value to it. Thus, runat asks the server to retain the values assigned to the attributes.

 

If you change 'vijay13' to 'vijay14' in the textbox and click on the button again, 'vijay14' will be displayed in the textbox. Thus, new values are restored.

 

We now change the name of the textbox from aa to aaa in a.aspx. On executing the whole program again, the textbox of a.aspx is displayed as empty. This occurs  because the names are different, and thus, they refer to different textboxes.

 

Restore the name of aa again and load a.aspx in the address bar. As  the textbox names now match, the earlier value of vijay14 is displayed again. The name and the id value of the form too can be changed without disturbing the above process.

 

To improve your grasp of the above proceedings, open another copy of the browser and load a.aspx. You will then notice that the two copies maintain distinct values. This implies that the web server is informed about the newly opened browser too.

 

This book will delve deeper into these concepts. So, continue reading if you wish to satiate your curiosity any further.

 

a.aspx

<%@ language=C# %>

<form action=a1.aspx>

<select name=item>

<option> Wood </option>

<option> Copper </option>

<option> Iron </option>

</select>

<input type= submit value=Click >

</form>

 

View Source

<form action=a1.aspx>

<select name=item>

<option> Wood </option>

<option> Copper </option>

<option> Iron </option>

</select>

<input type= submit value=Click >

</form>

 

To create a listbox, the HTML tag 'Select' is used. 'Select' requires 'option' as a sub-tag, where the values within the listbox are placed. We have the prerogative to pick out any of the items from the listbox, but when we click on the submit button, the name of the listbox is intialized to the value that has been selected.  Thus, item will be initialized to the value Copper, when Copper is selected. This feature is a slight deviation for HTML novices or for those with a frail memory, where HTML is concerned. There is no change in the aspx file other than the aspx directive with language as C#. Select the item as Copper and the url changes to

 

http://localhost/a1.aspx?item=Copper

 

a.aspx

<%@ language=C# %>

<form action="a.aspx" runat="server">

<asp:dropdownlist id="aa" runat=server>

<asp:listitem>wood</asp:listitem>

<asp:listitem>copper</asp:listitem>

<asp:listitem>steel</asp:listitem>

</asp:dropdownlist>

<asp:button text="Click a.aspx" runat="server" />

</form>

 

For the sake of completeness, we have shown how you can display a combo box using the tags asp:dropdownlist and asp:listitem, instead of the 'select the option' tag. It is more advisable to use these tags instead of the above displayed standard HTML tags.

 

We will gradually proceed to build a real life application in ASP+. Has it ever ceased to astonish you, as to how a different advertisement appears each time you visit the same website. The application given below clarifies this mystery.

 

a.aspx

<%@ language=C# %>

<form action="a.aspx" runat="server">

<asp:adrotator AdvertisementFile="a.xml" runat="server"/>

<asp:button text="Click" runat="server"/>

</form>

 

a.xml

<Advertisements>

   <Ad>

      <ImageUrl>/quickstart/aspplus/images/banner2.gif</ImageUrl>

   </Ad>

   <Ad>

      <ImageUrl>/quickstart/aspplus/images/banner3.gif</ImageUrl>

   </Ad>

</Advertisements >

 

Each time we click on the Click button, we come across a different advertisement of banner. How does this happen? To unravel this mystery, we first look at the HTML source that is generated by the server for the file a.aspx.

 

View-Source

<form name="ctrl0" method="post" action="a.aspx" id="ctrl0">

<input type="hidden" name="__VIEWSTATE" value="dDw3MTQ1NDk0MTs7Pg==" />

 

<a target="_top"><img src="/quickstart/aspplus/images/banner3.gif" border="0" /></a>

<input type="submit" name="ctrl2" value="Click" />

</form>

 

The anchor ( a ) and the image ( img ) tags are the newly inserted tags corresponding to asp:adrotator. The attribute AdvertisementFile="a.xml" directs the web server to a file, a.xml, which contains a series of img files that the web server is required to serve. a.xml must be in the same directory as a.aspx i.e c:\inetpub\wwwroot. The runat attribute retains the information for the web server.

 

An XML file is simply an HTML file. We start with a root or a starting tag called Advertisements. Within this, is located a tag called Ad, which contains another tag called ImageUrl. ImageUrl contains the images that are to be served in rotation. These images are present in the images subdirectory i.e. quickstart/aspplus/images, which is created while installing ASP+ and its samples.

 

a.aspx

<%@ language=C# %>

<form action="a.aspx" method="post" runat="server">

<script language="C#" runat=server>

void abc(Object a, EventArgs e)

{

Response.Write("hell");

}

</script>

<asp:textbox id="aaa" runat="server"/>

<asp:button type=submit text="Click" OnClick="abc" runat="server"/>

</form>

 

We have created a function abc that accepts two parameters; the first one is 'a' which looks like a class Object, and the second one is 'e' which looks like EventArgs. The asp:button tag is used with an additional attribute called OnClick, which is initialized to the abc function. This function is called, when the button is clicked.

The two controls viz. textbox and button, are visible when a.aspx is displayed in the browser window. View-Source displays the following:

 

View-Source

<form name="ctrl0" method="post" action="a.aspx" id="ctrl0">

<input type="hidden" name="__VIEWSTATE" value="YTB6MTk4ODc0NjcyX19feA==f2f03fae" />

<input name="aaa" type="text" id="aaa" />

<input type="submit" name="ctrl4" value="Click" type="submit" />

</form>

 

The OnClick attribute is not visible in the contents displayed by View-Source. Further, the function abc simply vanishes without a trace ! Where did they actually vanish? If you observe carefully, in the input tag for the button, the attribute type is displayed twice.

 

We now write vijay in the textbox and click on the button. The browser window displays 'hell', followed by the textbox that contains 'vijay', and then the View-Source displays the following:

 

View-Source

hell<form name="ctrl0" method="post" action="a.aspx" id="ctrl0">

<input type="hidden" name="__VIEWSTATE" value="YTB6MTk4ODc0NjcyX19feA==f2f03fae" />

<input name="aaa" type="text" value="vijay" id="aaa" />

<input type="submit" name="ctrl4" value="Click" type="submit" />

</form>

 

This proves the fact that when the button was clicked, the web server was asked to execute a.aspx. The button 'Click' has a function abc associated with it that displays 'hell'. So, IIS executes this function and then generates an HTML file with the output of the function abc. Furthermore, it remembers that the data entered in the textbox was 'vijay'. Hence, the value with the textbox is initialized to this value.

a.aspx

<%@ language=C# %>

<form action="a.aspx" method="post" runat="server">

<script language="C#" runat=server>

int i = 0;

void abc(Object a, EventArgs e)

{

i++;

Response.Write("hell " + i.ToString());

}

</script>

<asp:textbox id="aaa" runat="server"/>

<asp:button type=submit text="Click" OnClick="abc" runat="server"/>

</form>

 

The browser window shows the same controls as before. Before the button is clicked, the variable i is initialized to 0, and thereafter, the web server executes the function abc. Within the function abc, i is increased by one and then its value is displayed.

 

An int class has a function called ToString that converts a number into a String. The + sign concatenates two strings. Thus, in the first instance, we see 'hell 1', and the View-Source shows the following:

 

View-Source

hell 1<form name="ctrl0" method="post" action="a.aspx" id="ctrl0">

<input type="hidden" name="__VIEWSTATE" value="YTB6MTk4ODc0NjcyX19feA==f2f03fae" />

<input name="aaa" type="text" value="vijay" id="aaa" />

<input type="submit" name="ctrl4" value="Click" type="submit" />

</form>          

 

Each time we click on the button, the entire aspx file gets executed from the very beginning. Therefore, the value of the variable i gets initialized to zero everytime. This results in the text 'hell 1' being displayed each time. The variable i does not retain its previous values, because everything starts afresh whenever the button is clicked.

a.aspx

<%@ language=C# %>

<form action="a.aspx" method="post" runat="server">

<script language="C#" runat=server>

void abc(Object a, EventArgs e)

{

cc.Text = aa.Text + " " + bb.SelectedItem;

}

</script>

<asp:textbox id="aa" runat="server"/>

<asp:dropdownlist id="bb" runat=server>

<asp:listitem>Wood</asp:listitem>

<asp:listitem>Copper</asp:listitem>

<asp:listitem>iron</asp:listitem>

</asp:dropdownlist>

<asp:button type=submit text="Click" OnClick="abc" runat="server"/>

<asp:label id="cc" runat="server"/>

</form>

 

In the above example, we have introduced one more tag called asp:label, having the id of cc. This label, for the moment, does not get displayed on the screen. Its behaviour is similar to that of hidden types. We then enter the text 'vijay' in the textbox named aa, and select the option named Wood from the listbox called bb.

 

The Web Server first executes the function abc. Every textbox has a property called Text,which returns the text entered by the user. Thus, aa.Text will return 'vijay'. Setting aa.Text to 'Mukhi' will change 'vijay' to 'Mukhi'. Also, a listbox has a property called SelectedItem that returns the item selected. Thus, bb.SelectedItem returns the value 'Wood'.

 

It is our intent to display these details using the label control. Similar to the textbox, every label has a member or a property called Text. We initialize this property to the contents of the textbox and listbox. Hence, 'vijay Wood' is displayed in the browser window.

 

a.aspx

<%@ language=C# %>

<script language="C#" runat="server">

void Page_Load(Object Src, EventArgs E)

{

aa.Text = "Time is : " + DateTime.Now;

}

</script>

<asp:label id="aa" font-size="24" font-bold="true" runat=server/>

 

Output

Time is : 2001-03-22T19:08:46

 

View Source

<span id="aa" style="font-size:24px;font-weight:bold;">Time is : 2001-03-22T19:08:46</span>

 

In this program we have a tag called asp:label with an id of aa. No text is initially assigned to the label. Therefore, the text attribute is not specified. Instead, two new attributes are given, viz. the font-size and font-bold with the values of 24 and True, respectively.

 

As before, we did not expect our HTML file to display any labels, since no text value is assigned. But to our utter disbelief, we can see the current date and time displayed in bold, on our screen.

 

We shall now reveal a secret to you: The Web Server is programmed to call the function Page_Load in the beginning, whenever it is present in an aspx file. In this function, we change the Text property of the label aa to "Time is : " and to the value returned by DateTime.Now.

 

DateTime has a variable called 'Now' that returns the current date and time on our server. Hence, the contents in View-Source display the date and time in the specified font format, using the HTML span tag.

 

The essential point to be remembered is that the server is oblivious to C# code. Whenever the function Page_Load is present, it is executed prior to generating the page.

 

a.aspx

<%@ language=C# %>

<script language="C#" runat="server">

void Page_Load(Object Src, EventArgs E)

{

aa.Text = "vijay";

bb.NavigateUrl = "a1.aspx?cc=" + aa.Text;

}

</script>

<asp:hyperlink id="bb" font-size=24 runat=server>

Hi <asp:label id="aa" runat=server/> Click here

</asp:hyperlink>

 

We now have an asp hyperlink tag that is equivalent of the <a href=> </a> tag in HTML. It is given an id of bb. The file also contains a label called aa.

 

In the Page_Load function, the label is changed to vijay and the NavigateUrl property of the hyperlink bb is changed to a1.aspx?cc=vijay. Thus, the first screen merely displays 'Hi vijay Click here'. When you click on the anchor, a1.aspx is called with cc initialized to vijay.

 

a1.aspx

<%@ language=C# %>

<script language="C#" runat="server">

void Page_Load(Object s,EventArgs e)

{

aa.Text = Request.Params["cc"];        

}

</script>

Hi <asp:label id="aa" runat=server/>!

 

In the file a1.aspx, Page_Load is the first function to be called by the server. The function Request.Params is similar to Request.QueryString. It accepts the name of the parameter cc which is enclosed within square brackets, and returns its value, i.e. vijay. Consequently, the browser window displays the text 'Hi vijay'!

 

You are granted with great flexibility in performing a lot of activities using the Page_Load function.

 

a.aspx

<%@ language=C# %>

<script language="C#" runat="server">

void abc(Object Src, EventArgs E)

{

if (aa.Text != "")

{

Response.Redirect("a1.aspx?bb=" + aa.Text);

}

else

{

cc.Text = "Enter your name in the textbox!";

}

       

}

</script>

<form runat=server>

Name: <asp:textbox id="aa" runat=server/>

<asp:button text="Enter" Onclick="abc" runat=server/>

<p>

<asp:label id="cc" forecolor="red" font-bold="true" runat=server/>

</form>

 

a1.aspx

<%@ language=C# %>

<script language="C#" runat="server">

void Page_Load(Object s,EventArgs e)

{

aa.Text = Request.Params["bb"];        

}

</script>

Hi <asp:label id="aa" runat=server/>!

 

The above example performs many more error checks than its predecessor. Here, there is a textbox called aa and a simple button that has a label named 'Enter'. The Onclick attribute of this button points to the function abc. The label is named cc and displayed in red colour. It has no text associated with it.

 

Without entering any data in the textbox, you can click on the button to call the function. This function scrutinises the contents of the textbox attribute for a value. If the textbox contains some text, in other words, if it is not blank, the function Response.Redirect creates a new URL called a1.aspx, followed with the ? and abc=vijay and then travels to it. We are assuming that the text entered is vijay. If the textbox contents are blank, the text attribute of the label is displayed with a warning message in red.

 

The html code is totally unaware about the 'behind the scene' tasks carried out by the server. Hence, the View-Source displays a simple html file. Thus, error checks can be automated using the programming language. The above program also demonstrates that parameters can be passed to an aspx file.

 

a.aspx

<%@ language=C# %>

<script language="C#" runat="server">

void abc(Object Src, EventArgs E)

{

String a = System.Web.HttpUtility.UrlEncode(aa.Text, System.Text.Encoding.UTF8);

cc.Text = a;

}

</script>

<form runat=server>

Name: <asp:textbox id="aa" runat=server/>

<asp:button text="Enter" Onclick="abc" runat=server/>

<p>

<asp:label id="cc" forecolor="red" font-bold="true" runat=server/>

</form>

 

Output

vijay+mukhi+%2b

 

In the textbox, we have keyed in the text 'vijay mukhi +'. Thereafter, if we click on the button, the abc function calls another function UrlEncode, which accepts two parameters. The first parameter is the text written in the textbox aa.Text and the second parameter is System.Text.Encoding.UTF8, which is the encoding style used on the Internet.

 

A URL is used to signify a computer address. It cannot contain characters such as a space, the plus sign etc. Therefore, all these special characters are converted into a form that is acceptable in a URL.  To achieve this, C# has functions like UrlEncode, that converts a space into a + sign, and all other reserved characters into their ASCII equivalents in hex . In addition to this, it prefixes them with the % sign. This conversion is termed as URL encoding. Its reverse is termed as URL decoding. If the data received from the Internet is encoded, then it has to be decoded before it can be used in our programs.

 

Validation Controls

 

a.aspx

<%@ language=C# %>

<form action="a.aspx" runat="server">

<asp:RequiredFieldValidator ControlToValidate="aaa" errormessage="Please Write something" runat=server />

<asp:textbox id="aaa" runat="server"/>

<asp:button type=submit text="Click" runat="server"/>

</form>

 

In the browser, a textbox and a button are displayed. When we click on the button, the following error message is displayed 'Please Write something'. Here, we have created a simple error check. We offered the user a textbox where we expected him to enter some data. If, for any reason, he refuses to do so, we can prevent him from proceeding further.

 

To validate data, we use a new ASP.Net tag called asp:RequiredFieldValidator with the attribute ControlToValidate initialized to the control id. In our case, the control to be checked is the textbox, hence, aaa is given. The attribute errormessage of this new tag is provided with text of the error message that we desire to  display on the occurrence of an error.

 

In order to implement error checks, this is all that is required to be done by us. On implementing this error check, we receive an error message if the textbox is left blank. If you select the View-Source menuoption, you will be surprised to see a large number of lines of code written in a language called Javascript. This code is executed on your web browser.

View-Source

<form name="ctrl0" method="post" action="a.aspx" language="javascript" onsubmit="ValidatorOnSubmit();" id="ctrl0">

<input type="hidden" name="__VIEWSTATE" value="dDwtNTEwNzM4MzUzOzs+" />

<script language="javascript" src="/aspnet_client/system_web/1_0_2914_16/WebUIValidation.js"></script>

 

<span id="ctrl1" controltovalidate="aaa" errormessage="Please Write something" evaluationfunction="RequiredFieldValidatorEvaluateIsValid" initialvalue="" style="color:Red;visibility:hidden;">Please Write something</span>

 

<input name="aaa" type="text" value="kk" id="aaa" />

<input type="submit" name="ctrl2" value="Click" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" type="submit" />

<script language="javascript">

<!--var Page_Validators =  new Array(document.all["ctrl1"]);// -->

</script>

<script language="javascript">

<!--

var Page_ValidationActive = false;

if (typeof(clientInformation) != "undefined" && clientInformation.appName.indexOf("Explorer") != -1) {

    if (typeof(Page_ValidationVer) == "undefined")

        alert("Unable to find script library '/aspnet_client/system_web/1_0_2914_16/WebUIValidation.js'. Try placing this file manually, or reinstall by running 'aspnet_regiis -c'.");

    else if (Page_ValidationVer != "121")

        alert("This page uses an incorrect version of WebUIValidation.js. The page expects version 121. The script library is " + Page_ValidationVer + ".");

    else

        ValidatorOnLoad();

}

function ValidatorOnSubmit() {

    if (Page_ValidationActive) {

        ValidatorCommonOnSubmit();

    }

}

// -->

</script>

</form>

A massive program has been generated by the server.  If you go to the script sub-directory mentioned in the src attribute, aspnet_client/system_web/1_0_2914_16, you will find a file called WebUIValidation.js that contains almost 455 lines of code.

 

The salient concept to be grasped here is that, the server is not called upon for conducting error checks, as this process takes too long. Instead, code that can be executed by the client is generated. Further, this code is generated in Javascript (invented by Netscape), which is a language that is compatible with all browsers. You can use the Microsoft version of Javascript i.e. Jscript, in ASP.Net, in lieu of the C# programming language.

 

The crucial concept that has been implemented is that, it is more sensible for the browser to carry out validations and then send the corrected data to the server for processing. If the entire responsibility of data validation is assigned to the server, it would have to send the data to and fro very often, resulting in data congestion. The browser speeds up the process of data validation and it ensures greater interaction with the user.

 

Whenever we click on the button, some Javascript code gets called, which executes the error checking.

 

a.aspx

<%@ language=C# %>

<form action="a.aspx" runat="server">

<asp:dropdownlist id="aa" runat=server>

<asp:listitem><!--Choose--></asp:listitem>

<asp:listitem >Wood</asp:listitem>

<asp:listitem >Copper</asp:listitem>

<asp:listitem >Steel</asp:listitem>

</asp:dropdownlist>

<asp:RequiredFieldValidator ControlToValidate="aa" InitialValue="<!--Choose-->" errormessage="You must select something" runat=server/>

<asp:button type=submit text="Click" runat="server"/>

</form>

 

To perform similar error checks for a listbox or any other control, we enforce the use of the attribute InitialValue to ensure that the user selects some value from the listbox before clicking on the button. If none of the values is selected, an error message is displayed. You should make sure that the InitialValue contains some informative message. This is to ensure that if the user does not select any of the options, the error message that is displayed is meaningful.

 

The Web Forms framework has a repertoire of validation server controls that are used to validate input forms for errors. They also display relevant error messages which inform the user about any inaccuracies.

 

There is no difference in the procedures for adding a listbox control or a validation control to a form. So far, we have delved upon only one type of Validation. However, a large number of validations are possible. We shall deliberate over them in the pages to come. There is no restriction on adding multiple Validation controls to an HTML control. However, it is pertinent to note that not all HTML controls can be validated.

 

a.aspx

<html>

<head>

<script language="C#" runat=server>

void abc(Object S, EventArgs e)

{

if (Page.IsValid == true)

{

aa.Text = "Page is Valid!";

}

else

{

aa.Text = "Some of the required fields are empty";

}

}

</script>

</head>

<body>

<form runat="server">

<asp:Label ID="aa" text="fill it up" runat=server />

<ASP:RadioButtonList id=bb runat=server>

<asp:ListItem>a1</asp:ListItem>

<asp:ListItem>a2</asp:ListItem>

</ASP:RadioButtonList>

<asp:RequiredFieldValidator id="r1" ControlToValidate="bb" InitialValue="" runat=server>

*

</asp:RequiredFieldValidator>

<ASP:TextBox id=cc runat=server />

<asp:RequiredFieldValidator id="r2" ControlToValidate="cc" Width="100%" runat=server>

hey

</asp:RequiredFieldValidator>

<ASP:Button id=B1 text="Validate" OnClick="abc" runat=server />

</form>

</body>

</html>

 

Now we have presented a more complicated validation example. The two widgets that have been used in the form are:

 

     A radio button that displays two values

     A textbox.

 

We also have to apply a validation control to each of the controls. The first validation control has an asterick sign ( * ). The second validation control has the word 'hey'.

 

The validation ensures the follows:

 

     When no text is entered in the textbox, the word 'hey' is displayed in front of the textbox. When the user enters some text in the textbox, the word 'hey' disappears.

     When no option is chosen in the radio button, a red coloured asterix (*) is displayed in front of the radio button. When the user selects an option in the radio button, the * vanishes.

 

Finally, when we fill up both the controls, the page is considered valid, since all controls on the page now contain some value or the other.

 

Every ASP+ page has a free variable called Page.IsValid, that tells us if all the controls on the page contain valid data or meet the validation rules. If all the controls satisfy the validation rules, then and only then, the free variable Page.IsValid is assigned a value of True. Otherwise, by default, it is assigned the value of False.

 

Thus, after all the controls contain valid data, when we click on the button labeled Validate, IsValid is assigned the value True. Hence, the label displays the text 'Page is Valid'.

 

Code can be validated either on the server or on the client. ASP+ has no knowledge of the browser that is being used. But, if your browser supports dynamic HTML, then the HTML page that is generated will contain a large amount of code to be executed on the browser.

 

In such a situation, whenever we click on a submit button, before the data can be sent to the server, the browser code in your HTML file gets executed first. In case of any error, the form is not sent to the server. Therefore, the data is sent to the server only if it is free from all errors. This concept is known as Client Side Programming. Note that it is the Web Server that generates the client side verification code.

 

A URL is created when we click on the Submit button. Alternatively, the same URL can be keyed into the address bar by the user. There is no way that a web server can differentiate between these two actions. In both these situations, the Web Server will perform the same error checks at its end, regardless of the fact that the client has already carried out validation of all the fields.

 

a.aspx

<%@ language=C# ClientTarget=DownLevel  %>

<form action="a.aspx" runat="server" method=get>

<asp:RequiredFieldValidator ControlToValidate="aaa" errormessage="Please Write something" runat=server />

<asp:textbox id="aaa" runat="server"/>

<asp:button type=submit text="Click" runat="server"/>

</form>

 

View Source

<form name="ctrl0" method="get" action="a.aspx" id="ctrl0">

<input type="hidden" name="__VIEWSTATE" value="dDwtMTQ5NzczMjY1MDs7Pg==" />

 

&nbsp;

<input name="aaa" type="text" id="aaa" />

<input type="submit" name="ctrl2" value="Click" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" type="submit" />

</form>

 

On changing the value of the property ClientTarget to DownLevel, the contents displayed by View-Source menuoption do not contain the Javascript code generated by the Web Server. By default, this property has a value of UpLevel, which results in a request to the browser to perform error checking on the data entered by the user.

 

a.aspx

<%@ language=C# ClientTarget=DownLevel  %>

<html>

<head>

<script language="C#" runat=server>

void abc(Object S, EventArgs e)

{

if (Page.IsValid == true)

{

aa.Text = "Page is Valid!";

}

else

{

aa.Text = "Some of the required fields are empty";

}

}

</script>

</head>

<body>

<form runat="server">

<asp:Label ID="aa" text="fill it up" runat=server />

<ASP:TextBox id=cc runat=server />

<asp:RequiredFieldValidator id="r2" ControlToValidate="cc" Width="100%" runat=server>

hey

</asp:RequiredFieldValidator>

<ASP:Button id=B1 text="Validate" OnClick="abc" runat=server />

</form>

</body>

</html>

 

This program is identical to its predecessor, but with a slight modification in that, the server performs all the validation checks and not the client. This has been achieved by assigning the value of Downlevel to the property ClientTarget.

 

Previously, the form had the filename a.aspx. However, this file name has been omitted here. Thus, when we click on the button the first time without entering any text, the function abc is called from the server. The function fills up the label with the message 'Some of the required fields are empty'.

 

When we enter some text in the textbox, and click on the button, the server receives a True value for Page.IsValid and thus, it changes the value of the label to 'Page is Valid!'. This happens only when the same form is sent back to the server.

 

a.aspx

<%@ language=C# ClientTarget=DownLevel%>

<html>

<head>

<script language="C#" runat=server>

void abc(Object Sender, EventArgs E )

{

ss.DisplayMode = (ValidationSummaryDisplayMode) aa.SelectedIndex;

}

</script>

</head>

<body>

<form runat="server">

Select Fruit

<ASP:RadioButtonList id=rr runat=server>

<asp:ListItem>Apples</asp:ListItem>

<asp:ListItem>Oranges</asp:ListItem>

</ASP:RadioButtonList>

<asp:RequiredFieldValidator id="r1" ControlToValidate="rr" ErrorMessage="Select one fruit " InitialValue="" runat=server>

*

</asp:RequiredFieldValidator>

Enter the quantity : <ASP:TextBox id=tt runat=server />

<asp:RequiredFieldValidator id="R2" ControlToValidate="tt" ErrorMessage="Quantity cannot be blank" runat=server>

*

</asp:RequiredFieldValidator>

<asp:ValidationSummary ID="ss" runat="server" HeaderText="You must enter a value in the following fields:"/>

 <ASP:Button id=Button1 text="Validate" runat=server />

<br>

<p>

Select display format for error messages

<asp:DropDownList id="aa" OnSelectedIndexChanged="abc" AutoPostBack =true runat=server >

<asp:ListItem>List</asp:ListItem>

<asp:ListItem selected>Bulleted List</asp:ListItem>

<asp:ListItem>Single Paragraph</asp:ListItem>

</asp:DropDownList>

</form>

</body>

</html>

 

We have a similar program as before, i.e. it has two controls, viz. a textbox and a radio button, with a validator for each of them. We have also added a new tag called <asp:ValidationSummary  that has the name ss, and some text in the attribute HeaderText.

 

Further, a listbox having the name aa is added which contains three items. Whenever the user changes the selection from the listbox, the function abc gets called.

 

The function changes the value of the attribute DisplayMode from the ValidationSummary tag, to one of the values stated in the listbox.

The listbox conatins a list of different formating style. The attribute SelectedIndex returns the option that is selected from the listbox.

 

 

Thus, each time we change the item selected from the listbox, we see the error summary displayed in different formats. As the client target property is assigned the value of DownLevel, all error checks take place only at the server. The AutoPostBack attribute is True. This gets converted into a select statement in HTML, with the Onchange attribute pointing to a function called __doPostBack.

 

<select name="aa" id="aa" onchange="javascript:__doPostBack('aa','')">

 

This function reads as follows:

 

function __doPostBack(eventTarget, eventArgument)

{

var theform = document.ctrl2

theform.__EVENTTARGET.value = eventTarget

theform.__EVENTARGUMENT.value = eventArgument

theform.submit()

}

 

The function merely calls Submit with all the form parameters. This reaches the server, which thereafter, generates a fresh page with the new format for the validation tag. This tag displays the list of errors only if IsValid is False.

 

a.aspx

<%@ Page clienttarget=downlevel %>

<html>

<head>

<script language="C#" runat="server">

void abc(Object s, EventArgs e)

{

if (Page.IsValid)

{

aa.Text = "Result: Valid!";

}

else

{

aa.Text = "Result: Not valid!";

}

}

void pqr(Object s,EventArgs e)

{

cc.Operator = (ValidationCompareOperator) bb.SelectedIndex;

cc.Validate();

}

</script>

</head>

<body>

<form runat=server>

<asp:TextBox Selected id="t1" runat="server">

</asp:TextBox><br>

<asp:TextBox id="t2" runat="server">

</asp:TextBox>

<asp:Button runat=server Text="Validate" onclick="abc" />

<asp:ListBox id="bb" OnSelectedIndexChanged="pqr" runat="server">

<asp:ListItem Selected Value="Equal" >Equal</asp:ListItem>

<asp:ListItem Value="NotEqual" >NotEqual</asp:ListItem>

<asp:ListItem Value="GreaterThan" >GreaterThan</asp:ListItem>

<asp:ListItem Value="GreaterThanEqual" >GreaterThanEqual</asp:ListItem>

<asp:ListItem Value="LessThan" >LessThan</asp:ListItem>

<asp:ListItem Value="LessThanEqual" >LessThanEqual</asp:ListItem>

</asp:ListBox>

<asp:CompareValidator id="cc" ControlToValidate ="t1" ControlToCompare = "t2" Type="String" runat="server"/>

<asp:Label ID="aa" runat="server"/>

</form>

</body>

</html>

 

There are two textboxes t1 and t2, a label aa and a button in the above program. The function abc is called whenever we click on the button. In the listbox bb, we have a large number of options, which have names that are similar to terms used for comparison, such as Greater Than, GreaterThanEqual, NotEqual etc.

 

A new ASP.Net tag <asp:CompareValidator is introduced in the program for the first time. This tag is given the name cc along with names of two other controls, whose values have to be compared. The controls t1 and t2 which are to be verified, are provided to the two attributes ControlToValidate and ControlToCompare.

 

Whenever the user changes the selected item from the listbox, the function pqr is called. This function initializes cc, a property operator, to the selected listbox value. Thereafter, the function Validate from CompareValidator control compares the values. If we choose 'Equal' in the listbox, the comparison that shall be carried out is, t1.Text == t2.Text. If it is True, then IsValid becomes True. Otherwise, it remains false.

 

Clicking on the button also results in the display of a message in the label. This message depends upon the value of IsValid. You can iteratively change the value in the listbox, and then click on the button to ascertain the result of the comparison.

 

The attribute type of the control cc is 'data type String' since, the values to be compared are of String type. However, you can modify the type of this property, to be able to compare other data types too.

 

Thus, to compare any two controls, validator control is reinforced in ASP.Net.

 

a.aspx

<%@ Page clienttarget=downlevel %>

<html>

<head>

<script language="C#" runat="server">

void abc(Object s, EventArgs e)

{

cc.Validate();

if (Page.IsValid)

{

aa.Text = "Result: Valid!";

}

else

{

aa.Text = "Result: Not valid!";

}

}

</script>

</head>

<body>

<form runat=server>

Value within the range of 10-20 :

<ASP:TextBox id=t3 value=20 runat=server />

<asp:Button runat=server Text="Validate" onclick="abc" />

<asp:RangeValidator id="cc" Type="Integer" ControlToValidate="t3" MaximumValue=20 MinimumValue=10 runat="server"/>

<asp:Label ID="aa" runat="server"/>

</form>

</body>

</html>

 

In the above program, we have used a validator called RangeValidator that checks whether the specified value falls within a range or not. The control that is to be validated, should be mentioned with the validator. Hence, ControlToValidate is initialized to t3. Furthermore, the maximum value and the minimum value of the range are to be provided. This is achieved by assigning these values to the attributes MaximumValue and MinimumValue, respectively. If the value contained in the control t3 does not fall within the specified range, IsValid becomes False.

 

When the page is loaded, the third textbox has the value 20. If we change the value in the third textbox to 15 and click on the button, the function abc is called, where the Validate function from the control cc, checks the value contained in the IsValid property.

 

Earlier, we had selected an operator from a listbox. Hence, the type was a String. In this case, since we are dealing with numbers, we change the Type property to integer.

 

a.aspx

<%@ Page clienttarget=downlevel %>

<html>

<head>

<script language="C#" runat="server">

void abc(Object s, EventArgs e)

{

cc.Validate();

if (Page.IsValid)

{

aa.Text = "Result: Valid!";

}

else

{

aa.Text = "Result: Not valid!";

}

}

</script>

</head>

<body>

<form runat=server>

Enter 5 digits

<ASP:TextBox id=t3 value=20 runat=server />

<asp:Button runat=server Text="Validate" onclick="abc" />

<asp:RegularExpressionValidator id="cc" runat="server" ControlToValidate="t3" ValidationExpression="^\d{5}$" />

</asp:RegularExpressionValidator>

<asp:Label ID="aa" runat="server"/>

</form>

</body>

</html>

 

The validator RegularExpressionValidator, which is introduced for the first time, is employed to validate control values. The validator simply requires the control to be validated, followed by a regular expression.

 

A Regular Expression generally appears like gibberish, since it contains special characters, but it can prove to be extremely powerful. A whole lot of books have been written on the simplicities and the complexities of Regular Expressions.

 

A regular expression is an expression that matches the data entered, with a pattern or a rule. In the above case, we want the user to enter a zip code that consists of only 5 numbers. He has to type in exactly 5 numbers, and they must be nothing but numbers. The regular expression will be ^\d{5}$. A caret sign ^ matches the input from the beginning of the line, while a dollar sign $ indicates the end. \d refers to a digit, and 5 in {} braces indicates 5 occurrences of the specified data type, i.e. 5 digits.  In simple terms, only 5 digits should be entered. Thus, '^/d{5}$' corresponds to 'start - check  5 digits - end'.

 

Let us look at another Regular Expression reflected on the next line.

^[\w-]+@[\w-]+\.(com|net|org|edu|mil)$

 

This expression verifies whether the e-mail address has been provided in the right format or not. The square brackets agree with any one of the many characters that it embodies. \w permits any character to be typed in. + means one or more, and the @ is an actual literal. Round brackets with value of ( aa | bb ) will check for either aa or bb. And as mentioned earlier, ^ marks the beginning of the line, while $ denotes the end of the line. The above Regular Expression will match an e-mail address exactly with the pattern specified.  This is just a preface to regular Expressions. There is a lot more to it than meets the eye at present. However, this introduction shall suffice for the time being.

 

a.aspx

<html>

<head>

<script language="C#" runat=server>

void pqr(object sender, EventArgs e)

{

aa.Text = "        ";

if (Page.IsValid)

aa.Text = "Page is valid!";

}

</script>

</head>

<body>

<form runat="server">

Enter a number greater than 100<p>

<asp:Label id=aa runat="server" /><br>

<asp:TextBox id=bb value=1000runat="server" />

<asp:CustomValidator id="cc" runat="server" ControlToValidate="bb"  ClientValidationFunction="abc" >

Number must be larger than 100

</asp:CustomValidator>

<p>

<asp:Button text="Validate" onclick="pqr" runat="server" />

<script language="javascript">

function abc(source, value)

{

if (value.Value > 100)

value.IsValid= true;

else

value.IsValid = false;

}

</script>

</form>

</body>

</html>

 

This program restricts data entry of any number less than 100. The error is checked at the client end and not at the server end. Here, you are introduced to one more validator tag <asp:CustomValidator, which accomplishes this task.

 

Conventionally, this tag is supplied with the control name to be validated, i.e. bb. This is followed by the name of the function, i.e. abc, with the attribute ClientValidationFunction.

 

The function abc is called whenever we click on the button. This function accepts two parameters, viz. source and value, where the first parameter is the control and the second one is the value typed in that control.  The code entered in this function is in Javascript, a language that is easier to learn than C#. In Javascript, variables do not have any type and functions are at liberty to return values of any type. If the  value.IsValid is initialized to True, the value in the control passes the validation check. If it is given a value of False, then it fails the validation check. Thus, if the value of variable source is larger than 100, a value of True is returned. If not then a value of False is returned. In the case of the function abc in Javascript, the View-Source menuoption shows code that is similar to what we had entered in aspx.

 

Thus, we have clearly demonstrated how to build your own custom error checks.

 

a.aspx

<html>

<head>

<script language="C#" runat=server>

void pqr(object sender, EventArgs e)

{

if (Page.IsValid)

{

aa.Text = "Page is valid!";

}

else

{

aa.Text = "Page is not valid! :-(";

}

}

void abc (object source, ServerValidateEventArgs value)

{

int n = Int32.Parse(value.Value);

if (n > 100)

    value.IsValid = true;

else

    value.IsValid = false;

}

</script>

</head>

<body>

<form runat="server">

<asp:Label id=aa runat="server" /><br>

<asp:TextBox id=bb runat="server" />

<asp:CustomValidator id="cc" runat="server" ControlToValidate="bb"  OnServerValidate="abc" >

Number must be larger than 100

</asp:CustomValidator>

<asp:Button text="Validate" onclick="pqr" runat="server" />

</form>

</body>

</html>

 

How do we achieve the same validation on the Server? To do so, CustomValidator takes an additional attribute called OnServerValidate, which is initialized to the function abc. Thus, each time we click on the button, data is retransmitted to the function abc, which is located on the server. On being called, the function abc checks the number. Thereafter, the function pqr is called. If the function abc returns true, IsValid in pqr becomes true.

 

C# code never gets executed on the client-side. It is the Web Server's responsibility to parse the C# code and create the correct HTML file. The View-Source menuoption will substantiate this fact.

 

Functional Controls

Buttons

 

a.aspx

<html>

<body>

<asp:Button id=Button1 runat="server" Text="vijay" onmouseover="this.style.backgroundColor='yellow'" onmouseout="this.style.backgroundColor='buttonface'"/>

<asp:Button id=Button2 runat="server" Text="mukhi"  onmouseover="this.style.fontWeight='bold'" onmouseout="this.style.fontWeight='normal'"/>

</body>

</html>

 

Output

 

A simple button can perform complicated tasks. The aspx file contains two button controls, labeled vijay and mukhi. Two different properties are associated with each of them.

 

The button with an id of Button1, which contains the text 'vijay', has properties called onmouseover and mouseout. The property mouseover is called when the mouse moves over the button. At this point, we are employing this property to change the background colour of the button to yellow. In the same vein, the property onmouseout is called when the mouse leaves the button. Here, we utilize this property to change the colour back to normal.

 

 

In the second button, having an id of button2 and the text 'mukhi', we take the same style property and change the font weight to bold. The 'this' keyword is optional.

 

a.aspx

<html>

<object id="i" class="System.Collections.ArrayList" runat=server/>

<script language="C#" runat=server>

void Page_Load(Object sender, EventArgs e) {

i.Add("a1");

i.Add("b1");

i.Add("c1");

l.DataSource = i;

l.DataBind();

}

</script>

<body>

<asp:datalist id="l" runat=server>

<ItemTemplate>

Vijay: <%# Container.DataItem %>

</Itemtemplate>

</asp:datalist>

</body>

</html>

 

Output

Vijay: a1 

Vijay: b1 

Vijay: c1 

 

The object tag in an aspx file is used to create an object. When we work with database controls, we will be creating an object that is an instance of a class ArrayList. Thus, by using the object tag with the class of System.Collections.ArrayList, we do not have to create an ArrayList object ourselves. The system accomplishes this for us. This object is called 'i' and is available in the Page_Load function.

 

The framework automatically adds the line  'i = new ArrayList'. Container.DataItem retrieves values from a list. This concept will be explained in greater detail in the database chapter. Thus, objects can be created, using a declarative tag based syntax.

Server-side comments

 

a.aspx

<%@ Page Language="C#"%>

<html>

<body>

hi   

<%--

Response.Write("hee);

--%>

</body>

</html>

 

Output

hi

 

One of the few things that we programmers really detest is, writing comments.

 

ASP+ offers us its unique facility of inserting comments in the server. Anything that is enclosed in <%-- tags, is ignored by the server. In the above case, we consciously avoided the double inverted commas to close the string, just to prove that the server ignores the comments. These comments are not sent to the browser either.

 

Thus, we can use these comments to prevent the server from executing some part of the code. 

 

a.aspx

<%@ Page Language="C#"%>

<html>

<body>

<!-- #Include File="a.txt" -->

<p>

Vijay Mukhi

<p>

<!-- #Include File="b.txt" -->

</body>

</html>

 

 

a.txt

<b>Sonal Mukhi</b>

 

b.txt

VMCI

 

Output

Sonal Mukhi

Vijay Mukhi

VMCI

 

We can display the contents of any text file within our aspx file, by using the reserved word 'include'. The filename that we specify, gets added to our asp file. Using this facility, common files that can be used by other ASP files, can be merged as and when required.

 

CheckBoxList

 

a.aspx

<html>

<head>

<script language="C#" runat="server">

 

void abc(object Source, EventArgs e)

{

for (int i=0; i < c.Items.Count; i++)

{

if ( c.Items[ i ].Selected )

l.Text = l.Text + c.Items[i].Text + "<br>";

}

}

void pqr(Object sender, EventArgs e)

{

if (cd.Checked == true)

{

c.RepeatDirection = RepeatDirection.Horizontal;

}

else

{

c.RepeatDirection = RepeatDirection.Vertical;

} 

}

</script>

</head>

<body>

<form runat=server>

<asp:CheckBoxList id=c runat="server">

<asp:ListItem>vijay</asp:ListItem>

<asp:ListItem>Sonal</asp:ListItem>

<asp:ListItem>vmci</asp:ListItem>

</asp:CheckBoxList>

<br>

<asp:CheckBox id=cd OnCheckedChanged="pqr" Text="Horizontal" AutoPostBack="true" runat="server" />

<p>

<asp:Button Text="Click" onclick="abc" runat="server"/>

<p>

<asp:Label id=l runat="server"/>

</form>

</body>

</html>

 

Output

 

We have used a control CheckBoxList with an id of 'c', with 3 items in the checkbox list. A simple checkbox has only one option, i.e. either true or false, whereas a CheckBoxList can store multiple checkboxes.

 

When we click on the button, the function abc gets called. In this function, we use Count, which is a member of the Items collection object, to control the iteration of the loops. Items[0] references the first checkbox, while Items[1] references the second checkbox, and so on.

 

Every checkbox has a Selected member, that identifies whether the checkbox has been selected or not. If it has been selected, the Text member of the checkbox is added to the text property of the label. Thus, when the page is loaded again, all the selected items are displayed.

 

When we click on a checkbox which has the id as 'cd', the function pqr gets called. Here, we are simply changing a member called RepeatDirection of the object 'c' to Horizontal or Vertical, depending upon the state of the checkbox.

 

It is again upto you to decide, whether you want to use a single checkbox or a list of checkboxes.

 

ImageButtons

 

a.aspx

<html>

<head>

<script language="C#" runat="server">

void abc(object Source, ImageClickEventArgs e)

{

Response.Write("hell");

}

</script>

</head>

<body>

<form runat=server>

<asp:ImageButton ImageUrl="/quickstart/aspplus/images/mango.jpg" onclick="abc" runat="server"/>

</form>

</body>

</html>

 

Output

hell

 

We can display a button, which has a picture on it. Whenever we click on this picture, it behaves like a normal button and calls function abc.

 

a.aspx

<html>

<head>

<script language="C#" runat="server">

void abc(object Source, ImageClickEventArgs e) {

Response.Write("x: " + e.X.ToString() + " y:" + e.Y.ToString());

}

</script>

</head>

<body>

<form runat=server>

<asp:ImageButton id=Button1 ImageUrl="/quickstart/aspplus/images/billg.gif" onclick="abc" runat="server" />

</form>

</body>

</html>

 

Output

x: 91 y:107

 

The guys at Microsoft and Mr. Bill Gates have a fine sense of humour. They have actually given us an example that allows us to hit/click Mr Gates with a mouse. It returns the positions at which you made the contact. We decided to play safe. When we click on the photo, it simply tells us the x and y co-ordinates of the position at which you clicked.

 

The ImageClickEventArgs has a large number of members, two of them being the x and y co-ordinates. These positions specify in pixels, the location at which we clicked on the image. What we do with these values, is left to our discretion.

 

a.aspx

<html>

<head>

<style>

.aa { border:0.6cm solid blue }

.bb { border:0.2cm solid gainsboro }

</style>

</head>

<body>

<form runat=server>

<asp:ImageButton runat="server" ImageUrl="/quickstart/aspplus/images/banana.jpg" onmouseover="this.style.border='0.2cm solid black';"  onmouseout="this.style.border='0.2cm solid gainsboro';"  />

<asp:ImageButton runat="server" ImageUrl="/quickstart/aspplus/images/banana.jpg" onmouseover="this.className='aa'" onmouseout="this.className='bb'"/>

<asp:ImageButton runat="server" ImageUrl="/quickstart/aspplus/images/banana.jpg" onmouseover="this.src='/quickstart/aspplus/images/mango.jpg';" onmouseout="this.src='/quickstart/aspplus/images/banana.jpg';"

/>

</form>

</body>

</html>

 

 

 

Output

 

We start off by displaying three image buttons, all of which display the same picture of a banana.

 

The first image displays a black border when the mouse moves over it. This is because, the onmouseover assigns a 0.2cm solid black value to the style.border property. When we move out of the image, the grey border reappears.

 

In the case of the second image, a style is created in the aspx program using the style tags. This requires two words or styles called aa and bb. We now use these styles in the mouse events. The use of style, forms the basis of CSS or cascading style sheets.

The third image uses the onmouseover event to change the banana to a mango. The onmouseover event changes the src property to execute this change in the image. The onmouseout event reverts the src property back to the banana.

 

Panel

 

a.aspx

<html>

<head>

<script language="C#" runat="server">

void pqr(object Source, EventArgs e)

{

p.Visible = false;

}

void abc(object Source, EventArgs e)

{

Response.Write("hell");

Label l = new Label();

l.Text = "Sonal ";

l.ID = "Sonalid";

p.Controls.Add(l);

p.Controls.Add(new LiteralControl("<br>Vijay Mukhi <br>"));

TextBox t = new TextBox();

t.Text = "VMCI ";

p.Controls.Add(t);

}

</script>

</head>

<body>

<form runat=server>

<asp:Panel id="p" runat="server" Height="200px" Width="300px">

Vijay Mukhi

</asp:Panel>

<asp:Button Text="Add Controls" onclick="abc" runat="server"/>

<asp:Button Text="Hide" onclick="pqr" runat="server"/>

</form>

</body>

</html>

 

A Panel control places different controls in one widget. We have created a panel control called 'p', and initialized its height and width properties to specific values. Two buttons named Add Controls and Hide have also been introduced. Clicking on the Add button results in a call to the abc function.

 

Within this function, we first create a Label and initialize the Text member to Sonal. The text is given an id of Sonalid. After initializing the members with the values, the control is added to the Panel, by using Add function.

 

Similarly, an instance of a LiteralControl is created and added to the Panel. The text passed on to the constructor gets displayed in the Panel. Finally, a textbox is created.

 

Panel and many other controls have a property called Visible. When this property is set to false, it hides the control. This is one of the powerful features of a panel. By changing a single property, a large number of controls simply vanish. Hence, the look and feel of the page gets transformed completely.

 

Radio Buttons

 

a.aspx

<html>

<script language="C#" runat="server">

void SubmitBtn_Click(Object Sender, EventArgs e)

{

if (r1.Checked)

{

Response.Write("one");

}

else if (r2.Checked)

{

Response.Write("two");

}

else if (r3.Checked)

{

Response.Write("three");

}

}

</script>

<body>

<form runat=server>

<asp:RadioButton id=r1 Text="Vijay" Checked="True" GroupName="rrr" runat="server" />

<br>

<asp:RadioButton id=r2 Text="Mukhi" GroupName="rrr" runat="server"/>

<br>

<asp:RadioButton id=r3 runat="server" Text="Sonal" GroupName="rrr" />

<br>

<asp:button text="Submit" OnClick="SubmitBtn_Click" runat=server/>

</form>

</body>

</html>

 

Output

 

A checkbox is used whenever the answer is to be returned as either yes or no, i.e. true or false. If a choice has to be made from amongst multiple options, a radio button is used instead.

 

In this program, 3 radio buttons with ids r1, r2, r3 are created with some text. The checked property of the first radio button is set to true. These radio buttons are then grouped together by initializing the GroupName, to a common value named rrr.

 

When we click on the button, the function SubmitBtn_Click is called. Using the 'if' statement, the Checked property of each radio button, is determined and displayed using a Write statement. This is a tedious process. In a RadioButton Group, only one radio button can be chosen at a time.

 

Calendar

 

a.aspx

<html>

<head>

<script language="C#" runat="server">

void abc(object sender, EventArgs e) {

switch (c.SelectedDates.Count)

{

case (0):  

l.Text = "No dates are currently selected";

break;

case (1): 

l.Text = "The selected date is " + c.SelectedDate.ToShortDateString();

break;

 

case (7):  

l.Text = "The selection is a week beginning " + c.SelectedDate.ToShortDateString();

break;

default:  

l.Text = "The selection is a month beginning " + c.SelectedDate.ToShortDateString();

break;

}

}

</script>

</head>

<body>

<form runat=server>

<asp:Calendar id=c runat="server" onselectionchanged="abc" DayNameFormat="Short" SelectionMode="DayWeekMonth"

   TodayDayStyle-Font-Bold="True" DayHeaderStyle-Font-Bold="True" OtherMonthDayStyle-ForeColor="gray"

   TitleStyle-BackColor="#3366ff" TitleStyle-ForeColor="white"

   TitleStyle-Font-Bold="True" SelectedDayStyle-BackColor="#ffcc66"

   SelectedDayStyle-Font-Bold="True" NextMonthText = "<img src='/quickstart/aspplus/images/monthright.gif' border=0>"

   PrevMonthText = "<img src='/quickstart/aspplus/images/monthleft.gif' border=0>" SelectorStyle-BackColor="#99ccff"

   SelectWeekText = "<img src='/quickstart/aspplus/images/selweek.gif' border=0 onmouseover=this.style.backgroundColor='#ffcc66' onmouseout=this.style.backgroundColor='#99ccff'>"

   SelectMonthText = "<img src='/quickstart/aspplus/images/selmonth.gif' border=0 onmouseover=this.style.backgroundColor='#ffcc66' onmouseout=this.style.backgroundColor='#99ccff'>"

/>

<asp:Label id=l runat="server" />

</form>

</body>

</html>

 

Output

The selected date is 05/09/2001

 

We could write a thesis on the options of a calendar control. Some programmer must have spent years writing this control.

 

Irrespective of the week or day or month that we select, the function abc gets called. In this function, a member called c.SelectedDates.Count tells us the day or the month that was selected. This is displayed with a relevant message on the browser screen. Further, the date that has been selected is shown highlighted in the calendar.

 

a.aspx

<html>

<body>

<form runat=server>

<asp:Calendar runat="server" SelectionMode="DayWeekMonth"   SelectWeekText = "vijay" SelectMonthText = "month"/>

</form>

</body>

</html>

 

Output

 

 

We have a simple calendar that uses the SelectionMode property as DayWeekMonth. Thus, all the three entities viz. day, week and month are displayed and underlined. As we have initialized the property SelectWeekText to 'vijay', each time we click on it, the entire week gets highlighted. Similarly, when we click on the month, the entire month gets selected.

 

There is not a single aspect that has not been catered for in the calendar control. It is extremely comprehensive.

 

a.aspx

<html>

<head>

<script language="C#" runat="server">

void abc(object sender, DayRenderEventArgs e)

{

CalendarDay d = ((DayRenderEventArgs)e).Day;

Response.Write(d.Date.Month.ToString() + " " + d.Date.Day.ToString());

TableCell c = e.Cell;

String h = "Vijay " + d.Date.Day.ToString() + "<br>";

c.Controls.Add(new LiteralControl(h));

}

</script>

</head>

<body>

<form runat=server>

<asp:Calendar id=Calendar1 runat="server" ondayrender="abc"/>

</form>

</body>

</html>

 

Each time that the calendar displays a date, it calls a function specified in the property ondayrender. This function is passed a DayRenderEventArgs parameter named 'e'. This object has a property called Date, and has two members called Month and Day. These two members give the current month and day.

 

This function gets called for each and every date that is displayed. We simply use the Cell property to return a TableCell object. The Add function of the Controls member is used to add other controls to the Table Cell.

 

Here, we are simply adding a Literal Control with Vijay and the current Date. The Microsoft example adds a holiday. The basic idea is that we can add anything that we like, to the cell or the date that is displayed.

 

Hyperlink

 

a.aspx

<html>

<script language="C#" runat=server>

void Page_Load(Object sender, EventArgs e)

{

l.NavigateUrl = "/QuickStart";

}

</script>

<body>

<form runat=server>

<asp:hyperlink id=l runat="server">

Vijay Mukhi

</asp:hyperlink>

</form>

</body>

</html>

 

 

 

View Source

<html>

<body>

<form name="ctrl2" method="post" action="a.aspx" id="ctrl2">

<input type="hidden" name="__VIEWSTATE" value="YTB6MTQ5MzQ0OTE2OF9hMHpfaHo1ejJ4X2Ewel9oejV6MXhfYTB6YTB6aH

pOYXZpZ2F0ZVVybF8vUXVpY2tTdGFydHhfX3hfX3h4X3h4X3hfX3g=d6300be0" />

<a id="l" href="/QuickStart">

Vijay Mukhi

</a>

</form>

</body>

</html>

 

Output

Vijay Mukhi

 

A hyperlink control is similar to <a href tag in HTML. We have created a hyperlink tag called l. In the function Page_Load, we have initialized the property NavigateUrl to /Quickstart. We could have initialized this property in the tag itself. Since Page_Load gets called initially at the server end, the HTML file that gets generated, has this URL specified in the <a href...> tag.

 

The View-Source confirms that pure HTML files are generated by the web server. At times, we may have a dash of JavaScript. The hidden tag called ViewState is used to maintain state between the browser and the server. The value field uniquely identifies each browser session.

 

a.aspx

<html>

<head>

<script language="C#" runat="server">

void abc(Object sender, EventArgs e)

{

Response.Write("hell");

}

</script>

</head>

<body>

<form runat=server>

<asp:LinkButton Text="Vijay Mukhi" onclick="abc" runat="server"/>

</form>

</body>

</html>

 

Output

hell

Vijay Mukhi

 

We can have buttons of all types and sizes. The control LinkButton looks like a hyperlink, but it is actually a button. The common adage that "if it walks like a duck, quacks like a duck, it is a duck", does not hold water for a LinkButton. If we click on it, the function abc gets called. We are not redirected to another URL, as we may have expected.

 

a.aspx

<html>

<head>

<script language="C#" runat="server">

void abc(object Source, EventArgs e)

{

f.PostedFile.SaveAs("c:\\" + t.Value);

Response.Write("File uploaded successfully to c:\\"+ t.Value + " on the web server");

}

</script>

</head>

<body>

<form enctype="multipart/form-data" runat="server">

Select File to Upload:

<input id="f" type=file runat="server">

<p>

Save as filename :

<input id="t" type="text" runat="server">

<p>

<input type=button value="Upload" OnServerClick="abc" runat="server">

</form>

</body>

</html>

 

The input tag with the type initialized to 'file', has an id of 'f'. Since the type is file, we see a  textbox, as well as, a button labeled Browser. When we click on this button, we see a dialog box that enables us to choose the file name.

 

After selecting a file, click on the button labeled Upload. This calls the function abc, where the control 'f' calls a function SaveAs, using its property PostedFile. The function saves the file on the web server's hard disk in the root directory. Thereafter, we simply display a simple message, that the file has been copied in C:\. The <input type=file.. is handled locally by the browser.

 

a.aspx

<html>

<head>

<script language="C#" runat="server">

void Page_Load(object Source, EventArgs e)

{

if (Page.IsPostBack)

{

ss.InnerHtml="value: " + h.Value ;

}

}

void abc(object Source, EventArgs e)

{

h.Value=s.Value;

}

</script>

</head>

<body>

<form runat=server>

<input id="h" type=hidden value="Vijay" runat=server>

<input id="s" type=text size=40 runat=server>

<input type=submit value="Enter" OnServerClick="abc" runat=server>

<span id=ss runat=server>sonal mukhi</span>

</form> </body>

</html>

We have an HTML control, with an id of 'h' and type as 'hidden'. Hidden types are not displayed in the browser window. This control is given an initial value of 'Vijay'.

 

We then have a textbox named as 's', followed by a button. If we click on the button, the  function abc gets called. This function simply picks up the text entered into the textbox and assigns it to the hidden field.

 

The Page_Load function uses the span field 'ss' ,to display the value contained the hidden field. As Page_Load is called first, the span field displays the previous value of the textbox. This is because the function abc initializes the hidden control to the new value, subsequently. Thus, we can use hidden fields to transfer data from the web browser to the web server, keeping the user oblivious to it.