ASP.Net學習筆記004--基於ashx方式的ASP.Net開發1
來源:互聯網
上載者:User
以前寫的課程都沒有附上源碼,很抱歉!
課程中的源碼可以加qq索要:1606841559
技術交流qq1群:251572072
技術交流qq2群:170933152
也可以自己下載:
ASP.Net學習筆記004基於hx方式的ASP.Net開發1.zip
http://credream.7958.com/down_20144363.html
用例子說明
ashx和aspx是處理前台提交資料的兩種方式:
ashx:
建立/WebSite1
hello1.htm
<!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>
<title></title>
</head>
<body>
<form action="Hello1.ashx">
姓名:<input type="text" value="UserName" name="UserName"/>
<input type="submit" value="提交" />
<!--
伺服器只認name屬性,而且name屬性如果重複,會只提交第一個
id是給dom用的
-->
</form>
</body>
</html>
---------------------------------------------------------------------------
Hello1.ashx
<%@ WebHandler Language="C#" Class="Hello1" %>
using System;
using System.Web;
public class Hello1 : IHttpHandler {
public void ProcessRequest (HttpContext context) {
// context.Response.ContentType = "text/plain";//返回的資料是txt格式的
//這裡寫plain可能導致,瀏覽器識別成xml
context.Response.ContentType = "text/html";//表示返回的資料是html
//把原來的html寫到瀏覽器:
string username = context.Request["UserName"];//取得html端,傳回的name為UserName的值
context.Response.Write(@"<form action='Hello1.ashx'>
姓名:<input type='text' value='"+username+@"' name='UserName'/>
<input type='submit' value='提交' />
</form>");//把原來的資料寫到控制項中
//在C#中加一個@就表示多行文本
context.Response.Write("Hello World");
context.Response.Write(username );//寫回瀏覽器
}
public bool IsReusable {
get {
return false;
}
}
}
---------------------------------------------------------------------------
Hello2.htm
<!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>
<title></title>
</head>
<body>
<form action="Hello2.ashx">
姓名:<input type="text" value="UserName" name="UserName"/>
<input type="submit" value="提交" />
<!--
伺服器只認name屬性,而且name屬性如果重複,會只提交第一個
id是給dom用的
-->
</form>
</body>
</html>
---------------------------------------------------------------------------
Hello2.ashx
<%@ WebHandler Language="C#" Class="Hello2" %>
using System;
using System.Web;
public class Hello2 : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";
string fullPath = context.Server.MapPath("Hello2.htm");
string content = System.IO.File.ReadAllText(fullPath );
//直接存取這個檔案也會被調用
context.Response.Write(content);
string username=context .Request ["UserName"];
if (string.IsNullOrEmpty (username )){
context.Response.Write("直接進入");
}
else
{
context.Response.Write("提交進入");
}
// context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}
}
---------------------------------------------------------------------------