Using HTML elements

It is quite easy to let ASP use an HTML control. Basically, we put it in the pre-generated form in the ASP page, we give it a runat attribute set to "server", and that it. OK, when used in ASP context the HTML controls require a slight different setting.

For instance the multiple attribute of the select element has to be set to true to show that it is a multiple select, and not to "multiple" as the standard specify. It would be ASP itself to convert it to the HTML code expected on client side.

Here is an example where we create a sort of feedback page for a blog that is about computer programming. We create an HTML input text, myName, where the reader could enter his name; then a multiple select, myLanguages, for the programming languages used; another input text, myOther, for entering more programming languages; another select (but this one is not a multiple one), myInterest, to let the reader give a feedback; a button, myButton, to ask ASP to run the associated C# code; and finally a label, myLabel, where putting the result.

Here is the resulting ASP page:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
void click(Object s, EventArgs e)
{
myLabel.Text = "Feedback from "
+ (myName.Value.Count() != 0 ? myName.Value : "anonymous") + "<br />"
+ "preferred languages: ";

bool anyLanguage = false;
for (int i = 0; i < myLanguages.Items.Count; ++i)
{
if (myLanguages.Items[i].Selected)
{
anyLanguage = true;
myLabel.Text += myLanguages.Items[i].Text + " ";
}
}
if (anyLanguage == false)
myLabel.Text += "not specified";
myLabel.Text += "<br />";

if(myOther.Value.Count() != 0)
myLabel.Text += "Other: " + myOther.Value + "<br />";

myLabel.Text += "Has been the blog useful? " + myInterest.Value;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Feedback</title>
</head>
<body>
<form id="myForm" runat="server">
<div>
<h2>Feedback</h2>
<p>Name:<br /><input type="text" id="myName" runat="server" /></p>
<p>Which programming languages do you currently use?<br />
<select id="myLanguages" runat="server" multiple="true">
<option>C</option>
<option>C++</option>
<option>C#</option>
<option>Java</option>
<option>Perl</option>
<option>SQL</option>
<option>Other</option>
</select>
</p>
<p>If other, please specify:<br />
<input type="text" id="myOther" runat="server" /></p>
<p>Have you found anything interesting in here?<br />
<select id="myInterest" runat="server">
<option>Yes</option>
<option>No</option>
</select>
</p>
<p><button id="myButton" onserverclick="click" runat="server">Confirm</button></p>
<p><asp:Label id="myLabel" runat="server" /></p>
</div>
</form>
</body>
</html>

Relatively speaking, we have written quite a lot of C# code in this example.

No comments:

Post a Comment