restart ASP.NET(2)

第二章 使用标准控件

      这一部分的控件我不想多讲,不管是你通过Visual Studio的工具箱来拖动控件,在设计面板里添加事件,在F4中编辑属性;亦或是手动写asp标签,手动写属性(智能提示下属性一目了然),手动写事件。我只是建议初学者们,这两种方式都多加练习一下,你可以很熟练地拖控件,又能很熟悉控件的事件和属性,即使将来的开发中你根本用不到这些控件。

2.1 关于几个属性

            ■  AccessKey属性

            也许这个属性大部分的人都没用过,事实上这个属性也不常用,它的作用就是为控件添加快捷键进行访问。例如下列代码中的四个控件,分别指定了AccessKey为T, C, R, B,访问它们的时候使用Alt + AccessKey (比如TextBox1用 Alt + T)就能快速访问。AccessKey这个属性也来源于HTML,例如我在页面定义一个超链接 <a href=”http://www.google.cn” accesskey=”G”>google 搜索</a>,在Chrome浏览器中直接按Alt + G键就能访问这个链接。但是,不同的浏览器中使用AccessKey的方法是有些差异的:

            IE浏览器
            按住Alt键,点击accesskey定义的快捷键(焦点将移动到链接),再按回车.

            FireFox浏览器
            按住Alt+Shift键,点击accesskey定义的快捷键.

            Chrome浏览器
            按住Alt键,点击accesskey定义的快捷键.

            Opera浏览器
            按住Shift键,点击esc,出现本页定义的accesskey快捷键列表可供选择.

            Safari浏览器
            按住Alt键,点击accesskey定义的快捷键.

            当然,如果在一个页面中定义了多个TextBox,设置它们的AccessKey都为”T”,当我们使用快捷访问时,会在这些TextBox间切换。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StandardControl6.aspx.cs" Inherits="HelloWorld.Web.chapter2.StandardControl6" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AccessKey="T"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" AccessKey="C"/>
<asp:RadioButton ID="RadioButton1" runat="server" AccessKey="R"/>
<asp:Button ID="Button1" runat="server" Text="Button" AccessKey="B"/>
</div>
</form>
</body>
</html>

            ■  AutoPostBack属性

             Autopostback是一种机制(自动根据Web控件的一些事件,将页面自动发回服务器。在一些Web控件中,称为auto post back属性。如果设置为true ,当此控件的某事件发生时,将发送一个request到服务器。            
             TextBox的AutoPostBack的触发事件是在文本框内容改变后失去焦点(即使你对文本框进行了复杂的编辑后,如果值与编辑前相同,它仍然不会PostBack到服务器)。
             CheckBox的AutoPostBack是在选中或取消选中时触发。
             RadioButton的AutoPostBack事件触发有点奇怪,它并不像书上说说的在其选中或取消选中时自动的PostBack,如果在页面初次加载时,选中RadioButton,它是会自动PostBack的。但是如果这样一种情况:两个RadioButton,radio1设置了AutoPostBack属性为true,radio2没有设置AutoPostBack属性(默认为false),只有首次加载,选中radio1时,才会PostBack,其他情况下无论你如何点击这两个RadioButton都不会PostBack,我又在页面中加入一个CheckBox(AutoPostBack=”true”),却发生这样的情况:假设已经不是首次加载,当radio1未选中,radio2选中时,通过CheckBox先触发一次PostBack,然后选中radio1也会触发PostBack,其他任何情况下都不会导致radio1触发PostBack。

            ■  TabIndex属性

             TabIndex的值可以设置在1~32767之间,控件中的TabIndex属性等同于html中的tabindex属性,默认情况下控件的tabindex值为0,若为负值则控件将被排除在TAB序列之外。可以通过设置tabindex值改变tab键在控件中移动的顺序,切换的顺序总是从低到高。

            ■  SkinID属性

主题目录中的一个或多个外观文件包含控件可以使用的外观。SkinID 属性指定对控件应用这些外观中的哪一个。外观是特定于特定控件的;不能在不同类型的控件之间共享外观设置。
如果未设置 SkinID 属性,则控件将使用默认外观(如果定义了默认外观)。例如,如果为 Image 控件定义一个没有 ID 的外观,则该外观将应用到所有不显式通过 ID 引用外观且没有禁用主题的Image 控件。如果为 Image 控件定义一个具有 ID 的外观,则该外观仅应用到 SkinID 设置为此 ID 的 Image 控件。

如果主题目录中的外观文件中不包含具有指定 SkinID 的外观,则会在运行时引发 ArgumentException 异常。

 

            ■  Attributes属性

             获取与控件的属性不对应的任意特性(只用于呈现)的集合。

<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e) {
TextBox1.Attributes["onblur"]="javascript:alert('Hello! Focus lost from text box!!');";
}
</script>
</head>
<body>
<h3>Attributes Property of a Web Control</h3>
<form runat="server">
<asp:TextBox id="TextBox1" columns=54
Text="Click here and then tap out of this text box"
runat="server"/>
</form>
</body>
</html>

            ■  ClientID属性

            如果要在js中用到服务器控件,可以通过document.getElementId(“<%= Control.ClientID%>”)这种方式来获得,例如<asp:TextBox ID=”TextBox1” runat=”server” />,在js中以这种方式获取:var id = document.getElementId(“<%= TextBox1.ClientID%>”)

2.2 显示信息

      ASP.NET提供了两个用于显示文本的控件:Label和Literal控件。Literal仅仅显示简单的文本,Label还支持一些样式(通过F4查看控件拥有哪些属性)。设置Label控件的一些属性可以调节文本的样式,这里我要说的是Label提供了CssClass属性,我们更熟悉css,所以直接赋予其CssClass的值,要比在标签中一个一个设置属性要方便的多,而且一个一个设置属性,你将会看到一个很长的asp标签,里面充满了冗长的单词。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StandardControl.aspx.cs" Inherits="HelloWorld.Web.chapter2.StandardControl" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<style type="text/css">
.label_1
{
background: gray;
font-size: 24px;
color: #FFFFFF;
}
</style>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label" CssClass="label_1"></asp:Label>
</div>
</form>
</body>
</html>

      运行页面以后,通过查看Source Code,我们一看到<span class="label_1" id="Label1">Label</span>这样的代码,Label控件最终被转换为HTML的span标签。但是有一种情况下Label控件生成的HTML标签不是span,而是label:为Label控件指定AssociatedControlID。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StandardControl2.aspx.cs" Inherits="HelloWorld.Web.chapter2.StandardControl2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label2" AssociatedControlID="TextBox1" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>

      下面的Label2关联TextBox1,在客户端将生成这样的代码<label id="Label2" for="TextBox1">Label</label>。AssociatedControlID的作用是能够把label标签和它指定的控件关联起来,当我们点击Label2的时候,TextBox1将会自动获得焦点。当然这也可以通过纯HTML实现,在HTML的label标签中加入for属性,这里我们也就知道for属性的含义了。

<form method="post" action="">
<label for="textbox1">关联Label</label>
<input type="text" id="textbox1"/>
<input type="text" id="textbox2"/>
</form>

2.2 接收输入控件

      2.21 TextBox控件

            TextBox控件提供了三种模式,SingleLine、MultiLine和Password(TextBox的TextMode属性)。

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" TextMode="Password"></asp:TextBox>

            这三种模式实际上是对下面代码中三种HTML表单的封装。

<form method="post" action="">
<input type="text" id="textbox1"/>
<textarea id="textarea1">多行模式</textarea>
<input type="password" id="textbox2"/>
</form>

            关于TextBox的其他属性和事件我就不再赘述了,详情可以参考MSDN TextBox类

      2.22 CheckBox控件(复选框)

            CheckBox控件就是HTML中的<input type=”checkbox” />。下面的代码提供了简单的记住文本的功能。CheckBox详情可以参考MSDN CheckBox类

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StandardControl4.aspx.cs" Inherits="HelloWorld.Web.chapter2.StandardControl4" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Button1_Click(object sender, EventArgs args)
{
if (this.CheckBox1.Checked)//如果选中了CheckBox,TextBox2的将显示TextBox1的文本
{
TextBox2.Text = TextBox1.Text;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" Text="remember me?"/>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>

      2.23 RadioButton控件(单选框)

            RadioButton控件在HTML中就是<input type=”radio” />。RadioButton控件总是成组出现,并且一次只能选择一个。详情请参考MSDN RadionButton类

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StandardControl5.aspx.cs"
Inherits="HelloWorld.Web.chapter2.StandardControl5" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Button1_Click(object sender, EventArgs args)
{
string result = string.Empty;
if (this.RadioButton1.Checked)
{
result = this.RadioButton1.Text;
}else if (this.RadioButton2.Checked)
{
result = this.RadioButton2.Text;
}else if (this.RadioButton3.Checked)
{
result = this.RadioButton3.Text;
}else
{
result = this.RadioButton4.Text;
}
this.Label1.Text = result;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul>
<li>你目前在哪里?</li>
<li><asp:RadioButton ID="RadioButton1" runat="server" Text="苹果" GroupName="Choice"/></li>
<li><asp:RadioButton ID="RadioButton2" runat="server" Text="谷歌" GroupName="Choice"/></li>
<li><asp:RadioButton ID="RadioButton3" runat="server" Text="微软" GroupName="Choice"/></li>
<li><asp:RadioButton ID="RadioButton4" runat="server" Text="其他" GroupName="Choice"/></li>
</ul>
<div><asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click"/></div>
<div><asp:Label ID="Label1" runat="server" Text=""></asp:Label></div>
</div>
</form>
</body>
</html>

      2.24 Button/LinkButton/ImageButton控件

      Button就是普通的按钮,LinkButton是带链接的按钮,ImageButton是带图片的按钮。这3个Button的行为基本类似,它们都具有一个PostBackUrl属性,默认情况下ASP.NET的控件请求完毕后都是回传到本页,可以通过设置PostBackUrl来实现跨页传送。而在普通的html页面中,表达跨页传送更轻松一些,直接在form元素中指定action属性。
      它们3个都具有CommandName属性,CommandArgument属性和Command事件。当在一个页面中出现多个Button控件时,我们不必为每个Button都添加一个Click事件,可以只写一个Command事件,让所有Button都指向这个事件,触发该事件时,会把CommandName和CommandArgument参数传到事件中,通过CommandName和CommandArgument来区分是哪个Button触发的事件。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StandardControl8.aspx.cs" Inherits="HelloWorld.Web.chapter2.StandardControl8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
//根据CommandName和CommandArgument来判断是哪个Button触发的事件
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
switch(e.CommandName)
{
case "Sort":
// Call the method to sort the list.
Sort_List((String)e.CommandArgument);
break;
case "Submit":
// Display a message for the Submit button being clicked.
Message.Text = "You clicked the Submit button";
// Test whether the command argument is an empty string ("").
if((String)e.CommandArgument == "")
{
// End the message.
Message.Text += ".";
}
else
{
// Display an error message for the command argument.
Message.Text += ", however the command argument is not recogized.";
}
break;
default:
// The command name is not recognized. Display an error message.
Message.Text = "Command name not recogized.";
break;
}
}
void Sort_List(string commandArgument)
{
switch(commandArgument)
{
case "Ascending":
// Insert code to sort the list in ascending order here.
Message.Text = "You clicked the Sort Ascending button.";
break;
case "Descending":
// Insert code to sort the list in descending order here.
Message.Text = "You clicked the Sort Descending button.";
break;
default:
// The command argument is not recognized. Display an error message.
Message.Text = "Command argument not recogized.";
break;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<h3>Button CommandName Example</h3>
Click on one of the command buttons.
<br><br>
<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>
&nbsp;
<asp:Button id="Button2"
Text="Sort Descending"
CommandName="Sort"
CommandArgument="Descending"
OnCommand="CommandBtn_Click"
runat="server"/>
<br><br>
<asp:Button id="Button3"
Text="Submit"
CommandName="Submit"
OnCommand="CommandBtn_Click"
runat="server"/>
&nbsp;
<asp:Button id="Button4"
Text="Unknown Command Name"
CommandName="UnknownName"
CommandArgument="UnknownArgument"
OnCommand="CommandBtn_Click"
runat="server"/>
&nbsp;
<asp:Button id="Button5"
Text="Submit Unknown Command Argument"
CommandName="Submit"
CommandArgument="UnknownArgument"
OnCommand="CommandBtn_Click"
runat="server"/>
<br><br>
<asp:Label id="Message" runat="server"/>
</form>
</body>
</html>

      LinkButton有一点特别,LinkButton本质上是超链接,一般的超链接请求方式是get,但是这里却是Post回发到本页面,通过查看Source,可以发现在生成的代码中有一段javascript代码导致了在点击LinkButton时,触发了Form的提交。例如下面一段简单的代码:

<script language="C#" runat="server">
protected void LinkButton1_Click(object sender, EventArgs e)
{
this.Label1.Text = this.LinkButton1.Text;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
<asp:Label ID="Label1" runat="server">123</asp:Label>
</form>
</body>
</html>

       生成的代码则是:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
</head>
<body>
<form name="form1" method="post" action="StandardControl10.aspx" id="form1">
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE5NTEyOTg2ODZkZMp7zh6VGp1aGdkhhoMpjpZET2qd" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgLlzdDxAwLM9PumD63NeWK0tdUgxExXhM11o/XBr2C+" />
</div>
<a id="LinkButton1" href="javascript:__doPostBack('LinkButton1','')">LinkButton</a>
<span id="Label1">123</span>
</form>
</body>
</html>

        关键之处就是这一句:theForm.submit();调用表单的提交事件。关于Button,LinkButton,ImageButton更详细的信息可以参照MSDN,MSDN上也有相关的事例:Button类LinkButton类ImageButton类。在MSDN中这些控件的地址一般是:http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.linkbutton(VS.80).aspx这种形式(只需要把linkbutton改成你想要查找的控件名),MSDN中很多基础属性和事件都讲得十分清楚。

posted @ 2010-03-20 00:24  Sunny Peng  阅读(1323)  评论(11编辑  收藏  举报