Asp.net前端和后台交互过程简述
1.首先打开VisualStudio新建一个Asp.net Web应用程序,模板选择为空;
2.添加一个html文件,在里面form表单中添加如下,注意form表单中的action属性为一般处理程序文件,表单在提交时自动将数据封装在Request对象中,并传给一般处理程序:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form action="Handler/LoginHandler.ashx" method="post">
用户名:<input type="text" name="userName"/><br/>
密 码:<input type="password" name="userPwd"/><br/>
<input type="submit" name="login" value="登录"/>
</form>
</body>
</html>
效果如下:
3.为程序新建一个Handler文件夹,再添加一个一般处理程序:LoginHandler.ashx,后台由一般处理程序(HttpHandler)读取前端网页提交的数据,代码如下:
public class LoginHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//获取前端数据信息
string userName = context.Request.Params["userName"];
string userPwd = context.Request.Params["userPwd"];
//后台进行验证
if (userName == "Herry" && userPwd == "12345")
context.Response.Write("登录成功!");
else
context.Response.Write("用户名或密码错误!");
}
public bool IsReusable
{
get
{
return false;
}
}
}
4,运行程序即可测试。