ASP.NET HelloWorld程序代码
Login.aspx:
<asp:TextBox ID="txt_UserName" runat="server" Width="166px"></asp:TextBox>
<asp:Button ID="bt_Login" runat="server" onclick="bt_Login_Click" Text="登录" />
Login.aspx.cs
protected void bt_Login_Click(object sender, EventArgs e)
{
if (this.txt_UserName.Text == String.Empty)
{
this.Session["UserName"] = "World!";
}
else
{
this.Session["UserName"] = this.txt_UserName.Text.ToString();
}
Response.Redirect("Default.aspx");
}
Default.aspx
<asp:Label ID="lb_content" runat="server"></asp:Label>
Defalut.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
this.lb_content.Text = "Hello," + Session["UserName"].ToString();
}
防止sql注入程序
SQLInjectionHelper.cs
public class SQLInjectionHelper
{
//获取POST数据
public static bool ValidUrlData(string request)
{
bool result = false;
//获取POST数据
if (request == "POST")
{
for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
{
result = ValidData(HttpContext.Current.Request.Form[i].ToString());
if (result)
{
break;
}
}
}
else //get请求
{
for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
{
result = ValidData(HttpContext.Current.Request.QueryString[i].ToString());
if (result)
{
break;
}
}
}
return result;
}
private static bool ValidData(string inputData)
{
//验证InputData是否包含恶意集合
if (Regex.IsMatch(inputData, GetRegexString()))
{
return true;
}
else
{
return false;
}
}
private static string GetRegexString() //获取正则表达式
{
//构造sql注入的关键字符串
string[] strBadChar = { "and","exec","insert","select","delete","update","count","from","drop","asc","char","or","%",";",":","'",""","-","chr","mid","master","truncate","char","declare","SiteName","net user","xp_cmdshell","/add","exec master.dbo.xp_cmdshell","net localgroup administrators"};
//构造正则表达式
string str_Regex = ".(";
for (int i = 0; i < strBadChar.Length - 1; i++)
{
str_Regex += strBadChar[i] + "|";
}
str_Regex+=strBadChar[strBadChar.Length-1]+").";
return str_Regex;
}
}
Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
bool result = false;
result = SQLInjectionHelper.ValidUrlData(Request.RequestType.ToUpper());
if (result)
{
Response.Write("您提交的数据有恶意字符!");
Response.End();
}
}
Test.aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="bt_Post" runat="server" Text="获取Post数据" OnClick="bt_Post_Click"/>
<asp:Button ID="bt_Get" runat="server" Text="获取Get数据" OnClick="bt_Get_Click"/>
Test.aspx.cs
protected void bt_Post_Click(object sender,EventArgs e)
{
}
protected void bt_Get_Click(object sender, EventArgs e)
{
Response.Redirect("Test.aspx?a=1&b=2&c=3");
}
控件介绍
HtmlInputButton.aspx
<form id="form1" runat="server">
<div>
<table>
<tr align='center'>
<td>
<input type="text" id="txt_a" size="2" value="1" maxlength="5" runat="server" />
</td>
<td>
+
</td>
<td>
<input type="text" id="txt_b" value=" 2" size="2" maxlength="5" runat="server"/>
</td>
<td>
=
</td>
<td>
<span id="sum" runat="server"></span>
</td>
</tr>
<tr align="center">
<td colspan="4">
<input id="bt_Add_Button" type="button" name="AddButton_Button" value="添加(button)" onserverclick="AddButton_Button_Click" runat="server"/>
<input id="bt_Add_Submit" type="submit" name="AddButton_Submit" value="添加(submit)" onserverclick="AddButton_Submit_Click" runat="server"/>
<input type="reset" id="bt_Reset" value="重置(reset)" runat="server" />
</td>
</tr>
</table>
</div>
</form>
<input id="bt_Image1" type="image" src="img/1.jpg" onmouseover="this.src='img/2.jpg'" onmouseout="this.src='img/1.jpg'"/>
HtmlInputButton.aspx.cs
protected void AddButton_Button_Click(object sender, EventArgs e)
{
sum.InnerHtml = ((Convert.ToInt32(txt_a.Value)) + (Convert.ToInt32(txt_b.Value))).ToString();
}
protected void AddButton_Submit_Click(object sender, EventArgs e)
{
sum.InnerHtml=(Convert.ToInt32(txt_a.Value)+Convert.ToInt32(txt_b.Value)).ToString();
}
文件上传
InputFile.aspx
<form id="form1" runat="server" method="post" enctype="multipart/form-data">
<div>
<input id="myFile" type="file" runat="server" />
<br />
<input id="submit1" type="submit" value="上传文件" runat="server" onserverclick="uploadClick" />
<br />
<div id="fileDatails" visible="false" runat="server">
文件名称:<span id="fileName" runat="server"></span>
<br />
文件类型:<span id="fileType" runat="server"></span>
<br />
文件大小:<span id="fileSize" runat="server"></span>
</div>
</div>
</form>
InputFile.aspx.cs
protected void uploadClick(object sender, EventArgs e)
{
fileName.InnerHtml = myFile.PostedFile.FileName;
fileType.InnerHtml = myFile.PostedFile.ContentType;
fileSize.InnerHtml = myFile.PostedFile.ContentLength.ToString();
fileDatails.Visible = true;
myFile.PostedFile.SaveAs("D:\myProject\vsProject\Solution3\uploadFile.txt");
}
多选框控件
HtmlCheckBox.aspx
<div id="div_chks" runat="server" style="border:1px solid red">
<asp:CheckBox ID="CheckBox1" runat="server" text="看书"/>
<asp:CheckBox ID="CheckBox2" runat="server" text="听音乐"/>
<br />
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click1" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
HtmlCheckBox.aspx.cs
protected void Button1_Click1(object sender, EventArgs e)
{
string str = string.Empty;
if (CheckBox1.Checked == true)
{
str += "1";
}
if (CheckBox2.Checked == true)
{
str += "2";
}
Label1.Text = str;
}
单选框控件
Danxuan.aspx
<div>
<input type="radio" id="radio1" runat="server" name="danxuan"/>选项1
<br />
<input type="radio" id="radio2" runat="server" name="danxuan"/>选项2
<br />
<input type="radio" id="radio3" runat="server" name="danxuan"/>选项3
<br />
<span id="spanRadio" runat="server"></span>
<input type="button" runat="server" id="submitRadio" onserverclick="submitClick" value="提交"/>
</div>
Dnaxuan.aspx.cs
protected void submitClick(object sender, EventArgs e)
{
if (radio1.Checked == true)
{
spanRadio.InnerHtml = "选中1";
}
else if (radio2.Checked == true)
{
spanRadio.InnerHtml = "选中2";
}
else if (radio3.Checked == true)
{
spanRadio.InnerHtml = "选中3";
}
}
图像控件
<input id=”btn_image” type=”image” src=”img/1.jpg”
onmouseover=”this.src=”img/2.jpg;” onmouseout=”this.src=”img/1.jpg”>
Hidden控件
Htmlhidden.aspx
<input id="text_hiddenDoc" type="hidden" value="初始隐藏" runat="server" />输入值:
<input id="txt_Doc" type="text" size="40" runat="server" />
<br />
<input type="submit" id="bt_save" value="保存" runat="server" onserverclick="bt_save_click"/>
<br />
<span runat="server" id="span1"></span>
Htmlhidden.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
span1.InnerHtml = "隐藏值:
"+text_hiddenDoc.Value+"
";
}
protected void bt_save_click(object sender,EventArgs e)
{
text_hiddenDoc.Value = txt_Doc.Value;
}
Select控件
<div>
选择一个颜色:
<select id="sl_Color" runat="server">
<option>red</option>
<option>green</option>
<option>blue</option>
<option>black</option>
</select>
<input id="submit1" type="submit" runat="server" value="提交" onserverclick="bt_submit_click" />
<br />
<input type="text" id="txt_color" runat="server" />
<input id="adToSelect" type="submit" value="添加一个颜色选项到Select控件" runat="server" onserverclick="bt_addToSelect_click"/>
<p>
<span id="span1" runat="server">颜色变化演示区域</span>
</p>
</div>
HtmlSelect.aspx.cs
protected void bt_submit_click(object sender, EventArgs e)
{
span1.Style["background-color"]=sl_Color.Value;
}
protected void bt_addToSelect_click(object sender, EventArgs e)
{
sl_Color.Items.Add(txt_color.Value);
}
使用数据流的形式输出图片
showImage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//获取文件地址参数
string file=Request.QueryString["file"].ToString();
FileStream steam = new FileStream(file, FileMode.Open);
//获取流的长度
long FileSize = steam.Length;
//定义一个二进制数组
byte[] Buffer=new byte[(int)FileSize];
steam.Read(Buffer,0,(int)FileSize);
steam.Close();
Response.BinaryWrite(Buffer);
steam = null;
}
新建showImg.aspx
<img id=”img1” runat=”server”>
在后台调用即showImg.aspx.cs下的page_load页面
img1.src=”showImage.aspx?file=”+Server.UrlEncode(“D:\myProject\vsProject\Solution3\timg.jpg”)
设置style特性以及其他属性
StyleSetting.aspx
<a id=”mysite” runat=”server’>
</a>
StyleSetting.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
mysite.Style["color"] = "#008800";
mysite.Style["font-size"] = "12pt";
mysite.Style["text-decotation"] = "none";
mysite.Style["font-style"] = "italic";
mysite.HRef = "http://www.baidu.com";
mysite.InnerText = "百度一下";
}
用程序动态创建控件
dongtaiBuildTag.aspx.cs page_load函数
HtmlAnchor mysite=new HtmlAnchor();
mysite.Style["color"] = "#008800";
mysite.Style["font-size"] = "12pt";
mysite.Style["text-decotation"] = "none";
mysite.Style["font-style"] = "italic";
mysite.HRef = "http://www.baidu.com";
mysite.InnerText = "百度一下";
this.Controls.Add(mysite);
运行结果与StyleSetting.aspx结果一样。
第三章 web标准服务器控件概述
3-1.aspx
<input type="button" id="test" value="保存" runat="server" onserverclick="saveClick" />
3-1.aspx.cs
protected void saveClick(object sender, EventArgs e)
{
Response.Write("我是保存按钮");
}
<asp:TextBox ID="textbox1" width="80%" Height="100px" runat="server"></asp:Text>
相同结果改写
(1)构造函数
textbox1.Height=new Unit(100);
textbox1.Width=new Unit("80%");
(2)静态方法
textbox1.Height=Unit.Pixel(100);
textbox1.Width=Unit.Percentage(80);
(3)对象
textbox1.Height=new Unit(100,UnitType.Pixel);
textbox1.Width=new Unit(80,UnitType.Percentage);
通过上述方法可以将同一单位赋值给多个控件
Unit myUnit=new Unit(100,UnitType.Pixel);
textbox1.Height=myUnit;
textbox2.Width=myUnit;
textbox3.Height=myUnit;
枚举
textbox1.TextMode=TextBoxMode.SingleLine;
颜色
(1)
int alpha=255;
int red=255;
int green=255;
int blue=0;
Button1.BackColor=Color.FromArgb(red,green,blue);
Button1.BackColor=Color.FromArgb(alpha,red,green,blue);
(2)
Button1.BackColor=Color.FromName(Red);
(3)
Button1.BackColor=Color.Red;
(4)
Button1.BackColor=ColorTranslator.FromHtml("red");//也可以是十六进制
字体
Button1.Font.Name="微软雅黑";
Button1.Font.Bold=true;//启用粗体
字体集合
string[] fontName={"微软雅黑","宋体","黑体"};
Button1.Font.Names=fontName;
字体大小设置
(1)
Button1.Font.Size=FontUnit.XSmall;
(2)
<asp:Button runat="server" Text="Butoon" ID="Button2">
Button2.Font.Size=FontUnit.Point(16);
(2)
<asp:Button runat="server" Text="Butoon" Font-Names="微软雅黑" Font-Bold="true" Font-Size="X-Small">
默认按钮
form属性的defaultbutton="Button1",按钮控件的ID
例子:
<form defaultbutton="button">
<asp:Button runat="server" Text="Butoon" ID="button">
<asp:Button runat="server" Text="Butoon" ID="Button2">
//默认按钮为第一个ID为button的
</form>
数据显示控件
label控件
<sap:Label ID="lb_doc" Font-Names="微软雅黑" Font-Bold="true" width="50%" Text="初始文本" runat="server"><asp:Label>
代码控制
lb_doc.Text="我爱ASP.NET";
显示复杂的HTML内容
(1)
public string HTMLDecode(string s)
该方法用于对HTML编码的字符串进行解码,并且返回已经解码的字符串,然后将返回已经解码的字符串赋值给label控件进行显示。
lb_doc.Text=Server.HtmlDecode(str);
(2)
public string HtmlEncode(string s)
该方法是对字符串进行HTML编码并且返回已经编码的字符串
Literal控件
<asp:Literal ID="lb_doc" text="初始文本" runat="server">
</asp:Literal>
代码控制
lb_doc.Text="我爱ASP";
特点:不允许你向其内容应用样式,无法定位,不适合创建标题
<asp:Label ID="Label1" runat="server" Text="我是label控件"></asp:Label>
<asp:Literal ID="Literal1" runat="server" Text="我是Literal控件"></asp:Literal>
查看网页源代码:
<span id="Label1">我是label控件</span>
我是Literal控件
数据输入控件
TextBox控件
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Columns="30" Rows="20"></asp:TextBox>
TextBox1.Text="我爱ASP"
TextMode属性设置为Password可以确保其他人员观察用户输入密码时无法确知该密码
CheckBox控件
<asp:CheckBox ID="CheckBox1" runat="server" Text="测试复选框" TextAlign="Left" />
if(CheckBox1.Checked)
{
//被选中时的代码
}
代码控制
CheckBox1.Checked=true;
CheckBoxList控件
CheckBoxList控件可以再web页面上创建多个复选框,即你可以在CheckBoxList控件的开始标记和结束标记之间防止一个listItem元素来创建你所要显示的项。
在显示的设置上,可以使用RepeatLayout和RepeatDirection属性指定列表的显示方式
RepeatLayout设置为table(默认)则该列呈现一个表格,如果设置为flow,则该列表呈现时没有任何表结构
如果设置为OrderedList,则将该列表的每一个选项前加上一个数字编号,如果设置为UnorderedList,则将在该列表的每个选项上加一个小黑点
RepeatDirection默认为Vertical,垂直方向上呈现该列表。
设置为Horizontal,则可以再水平方向上呈现该列表
<asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatLayout="Flow" TextAlign="Left" RepeatDirection="Horizontal">
<asp:ListItem>选项1</asp:ListItem>
<asp:ListItem>选项2</asp:ListItem>
<asp:ListItem>选项3</asp:ListItem>
<asp:ListItem>选项4</asp:ListItem>
</asp:CheckBoxList>
for (int i=0;i<CheckBoxList1.Items.Count;i++)
{
if(CheckBoxList1.Items[i].Selected)
{
//处理选中的项
}
}
Radiobutton控件
<asp:RadioButton ID="RadioButton1" GroupName="sex" Text="男" runat="server" />
<asp:RadioButton ID="RadioButton2" GroupName="sex" Text="女" runat="server" />
<asp:RadioButton ID="RadioButton3" GroupName="sex" Text="双性" runat="server" />
<asp:RadioButton ID="RadioButton4" GroupName="sex" Text="未知" runat="server" />
if(RadioButton1.Checked)
{
//处理代码
}
RadioButton1.Checked=true;
HTML源码
<input id="RadioButton1" type="radio" name="sex" value="RadioButton1" /><label for="RadioButton1">男</label>
<input id="RadioButton2" type="radio" name="sex" value="RadioButton2" /><label for="RadioButton2">女</label>
<input id="RadioButton3" type="radio" name="sex" value="RadioButton3" /><label for="RadioButton3">双性</label>
<input id="RadioButton4" type="radio" name="sex" value="RadioButton4" /><label for="RadioButton4">未知</label>
RadiobuttonList控件
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatLayout="OrderedList" RepeatDirection="Vertical" TextAlign="Right">
<asp:ListItem>单选</asp:ListItem>
<asp:ListItem>单选</asp:ListItem>
<asp:ListItem>单选</asp:ListItem>
<asp:ListItem>单选</asp:ListItem>
</asp:RadioButtonList>
string value=string .Empty;
if(RadioButtonList1.SelectedIndex>-1)
{
value=RadioButtonList1.SelectedItem.Text;
}
数据提交控件
Button控件
<asp:Button ID="bt_save" runat="server" Text="保存" OnClick="bt_Save_Click"/>
<asp:Button ID="Button1" runat="server" Text="保存" CommandName="Submit" OnClick="bt_Save_Click" />
protected void bt_Save_Click(object sender,EventArgs e)
{
//事件处理程序
}
设置CommandName属性来创建Command按钮,command按钮命令与按钮关联
<asp:Button ID="SortAscendingButton" Text="数据排序" CommandName="Sort" CommandArgument="Ascending" OnCommand="CommandBtn_Click" runat="server">
protected void CommandBtn_Click(object sender,CommandEventArgs e)
{
Response.Write("CommandName:"+e.CommandName+"CommandArgument:"+e.CommandArgument);
}
ImageButton控件
<asp:ImageButton ID="ImageButton1" runat="server" AlternateText="保存" ImageAlign="Middle" ImageUrl="img/1.jpg" OnClick="buton_click" />
LinkButton控件
<asp:LinkButton ID="LinkButton1" runat="server">保存</asp:LinkButton>
图像显示控件
<asp:Image ID="Image1" runat="server" AlternateText="演示图片(图片说明文字)" ImageUrl="img/timg.jpg"/>
ImageMap控件
日常编程中主要使用它的HotSpotMode、HotSpotS属性和Onclick事件
(1)
HotSpotMode属性。热点模式
1.NotSet 未设置项,虽然名为未设置,但其实默认情况下会执行定向操作,定向到你所指定的url地址去。
如果未指定url地址,那默认将指向到自己的web应用程序根目录
2.Navigate 定向操作。定向到指定的url地址去,如果未指定url地址,那默认将指向到自己的web应用程序根目录
3.PostBack 回发操作项。然后点击热点区域,将执行后面的Onclick事件
4.Inactive 无任何操作,相当于没有热点区域的普通图片
(2)HotSpotS属性
它有CircleHotSpot,RectangleHotSpot,和PolygonHotSpot这三个子类。
如果要自己定义类型,该类型必须继承HotSpot类。
(3)Onclick事件
对热点区域的点击事件经常在HotSpotMode为PostBack时用到
TestImageMap1.aspx
<asp:ImageMap ID="ImageMap1" runat="server" ImageUrl="img/timg.jpg" AlternateText="控件例子">
<asp:RectangleHotSpot NavigateUrl="http://www.baidu.com" AlternateText="连接到百度" Top="0" Left="0" Bottom="35" Right="90"/>
<%--HotSpotMode="Navigate" Top="0" Left="0" Bottom="35" Right="90"--%>
<asp:RectangleHotSpot NavigateUrl="http://www.google.com" AlternateText="连接到谷歌" Top="0" Left="90" Bottom="35" Right="180" />
<asp:RectangleHotSpot NavigateUrl="http://www.sina.com" AlternateText="连接到新浪" Top="35" Left="0" Bottom="70" Right="180" />
</asp:ImageMap>
TestImageMap2.aspx
<asp:ImageMap ID="ImageMap1" runat="server" ImageUrl="img/timg.jpg" AlternateText="控件例子" HotSpotMode="PostBack" OnClick="ImageMap1Click">
<asp:RectangleHotSpot HotSpotMode="PostBack" PostBackValue="http://www.baidu.com" AlternateText="连接到百度" Top="0" Left="0" Bottom="35" Right="90"/>
<asp:RectangleHotSpot HotSpotMode="PostBack" PostBackValue="http://www.google.com" AlternateText="连接到谷歌" Top="0" Left="90" Bottom="35" Right="180" />
<asp:RectangleHotSpot HotSpotMode="PostBack" PostBackValue="http://www.sina.com" AlternateText="连接到新浪" Top="35" Left="0" Bottom="70" Right="180" />
</asp:ImageMap>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
TestImageMap2.aspx.cs
protected void ImageMap1Click(object sender, ImageMapEventArgs e)
{
Label1.Text = e.PostBackValue + " clicked";
}
文件上传控件
TestFileUpload.aspx
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="上传" OnClick="UploadButton_click" />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
TestFileUpload.aspx.cs
protected void UploadButton_click(object sender, EventArgs e)
{
string savePath = @"D:\myProject\vsProject\Solution3";
if(!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
if (FileUpload1.HasFile)
{
//获取上传文件名称
string filename = FileUpload1.FileName;
//获取要上传的文件保存完整路径
savePath += filename;
//执行文件上传操作
FileUpload1.SaveAs(savePath);
Label1.Text = "你上传的文件保存在" + savePath;
}
else
{
Label1.Text = "你没有指定要上传的文件";
}
}
文件上传类型限制
(1)
protected void UploadButton_click(object sender, EventArgs e)
{
string savePath = @"D:\myProject\vsProject\Solution3";
string fileType = string.Empty;
if(!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
if (FileUpload1.HasFile)
{
//获取上传文件名称
string filename = FileUpload1.FileName;
//获取文件的类型转换为小写
fileType = Path.GetExtension(filename).ToLower();
if (fileType == ".jpg" || fileType == ".gif" || fileType == ".txt")
{
//获取要上传的文件保存完整路径
savePath += filename;
//执行文件上传操作
FileUpload1.SaveAs(savePath);
Label1.Text = "你上传的文件保存在" + savePath;
}
else
{
Label1.Text = "只允许上传.jpg,.gif和.txt文件";
}
}
else
{
Label1.Text = "你没有指定要上传的文件";
}
}
(2)
protected void UploadButton_click(object sender, EventArgs e)
{
string savePath = @"D:\myProject\vsProject\Solution3";
string fileType = string.Empty;
bool fileTypeOk = false;
if(!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
if (FileUpload1.HasFile)
{
//获取上传文件名称
string filename = FileUpload1.FileName;
//获取文件的类型转换为小写
fileType = Path.GetExtension(filename).ToLower();
string[] allowedFileType = {".jpg",".gif",".txt" };
for (int i = 0; i < allowedFileType.Length;i++ )
{
if (fileType == allowedFileType[i])
{
fileTypeOk = true;
}
}
if (fileTypeOk)
{
//获取要上传的文件保存完整路径
savePath += filename;
//执行文件上传操作
FileUpload1.SaveAs(savePath);
Label1.Text = "你上传的文件保存在" + savePath;
}
else
{
Label1.Text = "只允许上传.jpg,.gif和.txt文件";
}
}
else
{
Label1.Text = "你没有指定要上传的文件";
}
}
文件大小上传限制:
可上传的最大文件大小取决于MaxRequestLength配置的值。
超过这个值就会上传失败,可以再web.config配置文件<system.web>节点里面设置他的值
<system.web>
<httpRuntime maxRequestLength="40960" executionTimeout="6000" />
</system.web>
maxRequestLength以kb为单位,可以上传的秒数
Calendar控件
<asp:Calendar ID="Calendar1" runat="server" BackColor="Green" OnSelectionChanged="change_click"></asp:Calendar>
protected void change_click(object sender, EventArgs e)
{
Response.Write("你选择的日期是:" + Calendar1.SlectDate.ToLongDateString());
}
HyperLink控件
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="http://www.baidu.com" Target="_blank">HyperLink连接</asp:HyperLink>
Panel控件
panelText.aspx
<asp:Panel ID="Panel1" runat="server" Width="260px" HorizontalAlign="Left" Wrap="true" GroupingText="员工基础信息">
姓名:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
电话:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
地址:
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
</asp:Panel>
<asp:panel ID="Panel2" runat="server" Width="260px" HorizontalAlign="Center" Wrap="true" Visible="false" GroupingText="员工附加信息">
工作经验:<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</asp:panel>
<asp:Button ID="Button1" runat="server" Text="显示员工附加信息" OnClick="showDetails"/>
panelText.aspx.cs
protected void showDetails(object sender, EventArgs e)
{
Panel2.Visible = true;
Button1.Visible = false;
}
定义具有默认按钮的窗体
panelTest2.aspx
<asp:Panel ID="Panel1" runat="server" Width="260px" HorizontalAlign="Left" Wrap="true" GroupingText="员工基础信息" DefaultButton="Save">
姓名:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
电话:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
地址:
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
</asp:Panel>
<asp:Button ID="Save" runat="server" Text="Button" />
</div>
当用户按下Enter键时,默认触发id为save的button的onclick事件
HiddenFiled隐藏域
HiddenFieldTest.aspx
<script type="text/javascript">
function PageLoad() {
form1.HiddenField1.value = form1.TextBox1.value;
};
</script>
<asp:Label ID="Lable1" runat="server">
</asp:Label>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<input type="submit" name="submitButton" value="更改隐藏域的值" onclick="PageLoad()" />
<asp:HiddenField ID="HiddenField1" runat="server" OnValueChanged="HiddenField_valueChanged"/>
HiddenFieldTest.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
HiddenField1.Value = "隐藏域的初始值";
Lable1.Text = "隐藏域的初始值为:"+HiddenField1.Value;
}
}
protected void HiddenField_valueChanged(object sender, EventArgs e)
{
Lable1.Text = "隐藏域的值被客户端修改为:"+HiddenField1.Value;
}
AdTotator控件
是一种在web页面上显示广告的方法。
先定义一个xml文件,存储广告信息
在app_data文件夹下新建Ad.xml,添加入信息
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements xmlns="http://schemas.microsoft.com/AspNet/AdRotator-Schedule-File">
<Ad>
<ImageUrl>~/img/1.gif</ImageUrl>
<NavigateUrl>http://www.baidu.com</NavigateUrl>
<AlternateText>去百度搜索</AlternateText>
<Impressions>10</Impressions>
<Keyword>baidu</Keyword>
</Ad>
<Ad>
<ImageUrl>~/img/2.gif</ImageUrl>
<NavigateUrl>http://www.baidu.com</NavigateUrl>
<AlternateText>去谷歌搜索</AlternateText>
<Impressions>20</Impressions>
<Keyword>Google</Keyword>
</Ad>
</Advertisements>
Ad.aspx
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile="~/App_Data/Ad.xml" Target="_blank" />
打开即可查看
表单验证控件
TestRequireFieldVaild.aspx
<asp:TextBox ID="Text1" runat="server" Text="请输入文本"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="Text1" Text="文本输入不能为空" runat="server" Display="Static" InitialValue="请输入文本"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="button1" runat="server" Text="提交数据"/>
范围验证控件
TestRangeValidator.aspx
<div>
请在文本框中输入数字1-20
<br />
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequireFieldValidator1" ControlToValidate="TextBox1" Text="文本输入不能为空" runat="server"></asp:RequiredFieldValidator>
<br />
<asp:RangeValidator ID="RangeValidator1" ControlToValidate="TextBox1" MinimumValue="1" MaximumValue="20" Type="Integer" Text="输入数字必须是1-20" runat="server"></asp:RangeValidator>
<br />
<asp:Button ID="Button1" Text="数据提交" runat="server" />
</div>
比较验证控件CompareValidator
TestCompareValidator.aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator" ControlToValidate="TextBox1" ValueToCompare="20" Type="Integer" Text="你输入的数字必须小于或者等于20" Operator="LessThanEqual"></asp:CompareValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="数据提交" />
TestCompareValidator2.aspx
<div>
TextBox1:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
TextBox2<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator" ControlToValidate="TextBox1" ControlToCompare="TextBox2" Type="Integer" Operator="LessThanEqual" Text="TextBox1的值必须小于2的值"></asp:CompareValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="数据提交" />
</div>
正则验证控件RegularExpressionValidator
TestRegularExpressionValidator.aspx
Email:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="RegularExpressionValidator" ControlToValidate="TextBox1" ValidationExpression=".@.{2,}..{2,}" Text="你的Email格式错误"></asp:RegularExpressionValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="提交数据" />
自定义逻辑验证控件CumstomValidator
TestCumstomValidator.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestCumstomValidator.aspx.cs" Inherits="_4.TestCumstomValidator" %>
<!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>
<script type="text/javascript">
function ValidationFunctionName(source, arguments) {
//客户端验证代码
}
function ClientValidate(source, arguments) {
if ((arguments.Value % 2) == 0) {
arguments.IsValid = true;
}
else {
arguments.IsValod = false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Text="请输入一个数字"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1" ClientValidationFunction="ClientValidate" OnServerValidate="ServerValidation" Text="你输入的数字不是2的倍数" ForeColor="green"></asp:CustomValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="提交数据" />
</div>
</form>
</body>
</html>
TestCumstomValidator.aspx.cs
protected void ServerValidation(object source, ServerValidateEventArgs arguments)
{
try
{
int i = int.Parse(arguments.Value);
arguments.IsValid = ((i % 2) == 0);
}
catch
{
arguments.IsValid = false;
}
}
验证信息显示ValidationSummary
ValidationSummary.aspx
<div>
文本:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="文本输入不能为空" ControlToValidate="TextBox1" Text=""></asp:RequiredFieldValidator>
<br />
数字:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="输入的数字必须为1-20" ControlToValidate="TextBox2" Type="Integer" MinimumValue="1" MaximumValue="20" Text=""></asp:RangeValidator>
<br />
Email:<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="你的Email地址格式错误" ControlToValidate="TextBox3" ValidationExpression=".@.{2,}..{2,}" Text=""></asp:RegularExpressionValidator>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="true" DisplayMode="BulletList"/>
<asp:Button ID="Button1" runat="server" Text="数据提交" />
</div>
验证控件编程实战
TestRangeValidator1.aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="RangeValidator" ControlToValidate="TextBox1" EnableClientScript="false"></asp:RangeValidator>
<asp:Button ID="Button1" runat="server" Text="提交数据" OnClick="button1_click" />
TestRangeValidator1.aspx.cs
protected void button1_click(object sender,EventArgs e)
{
RangeValidator1.MaximumValue = "20";
RangeValidator1.MinimumValue = "1";
RangeValidator1.Type = ValidationDataType.Integer;
RangeValidator1.Validate();
if (!RangeValidator1.IsValid)
{
RangeValidator1.ErrorMessage = "你输入的数字必须在1-20内";
}
}
开发自己的验证控件
StringValidator.cs
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
/// <summary>
/// StringValidator 的摘要说明
/// </summary>
public class StringValidator : BaseValidator
{
public StringValidator()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
private static bool ValidData(string inputData)
{
if (Regex.IsMatch(inputData, GetRegexString()))
{
return false;
}
else {
return true;
}
}
private static string GetRegexString()
{
//构造sql注入的关键字符串
string[] strBadChar = { "and", "exec", "insert", "select", "delete", "update", "count", "from", "drop", "asc", "char", "or", "%", ";", ":", "'", """, "-", "chr", "mid", "master", "truncate", "char", "declare", "SiteName", "net user", "xp_cmdshell", "/add", "exec master.dbo.xp_cmdshell", "net localgroup administrators" };
//构造正则表达式
string str_Regex = ".(";
for (int i = 0; i < strBadChar.Length - 1; i++)
{
str_Regex += strBadChar[i] + "|";
}
str_Regex += strBadChar[strBadChar.Length - 1] + ").*";
return str_Regex;
}
protected override bool EvaluateIsValid()
{
string value = this.GetControlValidationValue(this.ControlToValidate);
//throw new NotImplementedException();
return ValidData(value);
}
}
TestStringValidator.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestStringValidator.aspx.cs" Inherits="TestStringValidator" %>
<%@Register TagPrefix="custom" Namespace="WebSite" Assembly="4" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Height="80px"></asp:TextBox>
<br />
<custom:StringValidator id="StringValidator1" controltovalidate="TextBox1" text="你输入的文本里面有非法字符" runat="server"></custom:StringValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="数据提交" />
</div>
</form>
</body>
</html>
验证组
TestValidationGroup.aspx
<asp:Panel ID="Panel1" runat="server" EnableTheming="true" Width="300" GroupingText="组一">
用户名:<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
runat="server"
ErrorMessage="请输入用户名"
ControlToValidate="UserName"
ValidationGroup="UserNameGroup"
>
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="数据提交" CausesValidation="true" ValidationGroup="UserNameGroup" />
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" EnableTheming="true" Width="300" GroupingText="组二">
地址:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator
ID="RequiredFieldValidator2"
runat="server"
ErrorMessage="请输入地址"
ControlToValidate="TextBox1"
ValidationGroup="AddressGroup"
>
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button2" runat="server" Text="数据提交" CausesValidation="true" ValidationGroup="AddressGroup" />
</asp:Panel>
第五章asp.net用户控件
161页
TestUserControl.ascx
<table style="width:100%;">
<tr>
<td>
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_selectChanged"></asp:Calendar>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label1" runat="server"></asp:Label>
</td>
</tr>
</table>
TestUserControl.ascx.cs
protected void Calendar1_selectChanged(object sender, EventArgs e)
{
Label1.Text = "你选择的日期是:" + Calendar1.SelectedDate.ToLongDateString();
}
Test.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<%@ Register Src="~/TestUserControl.ascx" TagName="TestUserControl" TagPrefix="ucl" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>测试TestUserControl控件</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ucl:TestUserControl ID="TestUserControl1" runat="server"/>
</div>
</form>
</body>
</html>
运行Test.aspx,即可显示日历
用户控件编程
HyperLinkControl.ascx
<asp:Panel ID="Panel1" runat="server" EnableTheming="true" Width="400px" GroupingText="网站友情链接" Font-Size="10pt">
<asp:HyperLink ID="HyperLink1" runat="server" OnLoad="HyperLink_Load"></asp:HyperLink>
</asp:Panel>
HyperLinkControl.ascx.cs
protected void HyperLink_Load(object sender,EventArgs e)
{
HyperLink1.Text = "本书官网";
HyperLink1.NavigateUrl = "http://www.baidu.com";
}
HyperLinkControl.aspx
<%@ Register TagPrefix="ucl" Src="~/HyperLinkControl.ascx" TagName="HyperLinkControl"%>
<ucl:HyperLinkControl runat="server"/>
给用户控件添加属性
HyperLinkControl.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
HyperLink1.Text = Text;
HyperLink1.NavigateUrl = Url;
}
}
private string text;
private string url;
public string Text
{
get
{
return text;
}
set
{
text = value;
}
}
public string Url
{
get
{
return url;
}
set
{
text = value;
}
}
HyperLinkControl.ascx
<asp:Panel ID="Panel1" runat="server" EnableTheming="true" Width="400px" GroupingText="网站友情链接" Font-Size="10pt">
<asp:HyperLink ID="HyperLink1" runat="server"></asp:HyperLink>
</asp:Panel>
HyperLinkControl.aspx
<%@ Register TagPrefix="ucl" Src="~/HyperLinkControl.ascx" TagName="HyperLinkControl"%>
<ucl:HyperLinkControl runat="server" Text="本书官网" Url="http://www.baidu.com"/>
184页码
网友评论