ASP.NET 笔记
基础
跳转页面及弹窗
跳转页面
Response.Redirect("UserInfo.aspx");
弹窗
Response.Write("<script> alert('内容不允许为空')</script>");
弹窗并跳转页面
Response.Write("<script language='javascript'>alert('弹出显示的信息!'); location=' 跳转的页面地址';</script>");
页面刷新
Response.Redirect(Request.Url.ToString());
RedirectURL传值、接值
跳转页面并传值
Response.Redirect("UserInfo.aspx?uid=1&pwd=2");
窗体加载接受
if (Request.QueryString["id"] != null&&Request.QueryString["pwd"] != null)
{
string id = Request.QueryString["id"].ToString();
string pwd = Request.QueryString["id"].ToString();
}
传值: Response.Redirect(“页面.aspx?变量名=值”) Response.Redirect(“页面.aspx?变量名=”+值)
多个值:Response.Redirect(“页面.aspx?变量名=值&变量名=值”)
接值(在另一个页面):Request.QueryString[“变量名”].ToString()
登录模块
placeholder="请输入用户" // 文本框灰色提示
TextMode="password" //密码框
判断控件是否被选中
//选中的话,累加值
foreach (Control Chhooby in Panel1.Controls)
{
//判断当前循环的控件是不是CheckBox类型
if (Chhooby.GetType().ToString().Equals("System.Web.UI.WebControls.CheckBox"))
{
//转换成CheckBox
CheckBox ck = (CheckBox)Chhooby;
// 判断是否被选中
if (ck.Checked)
{
str += ck.Text + ",";
}
}
}
//去掉最后一个, (截取字符串)
//Substring(截取的起始的位置,截取的长度)
str = str.Substring(0,str.Length-1);
DropDownList用法
动态绑定数据,并追加一项
设置DropDownList属性 AppendDataBoundItems="True"
绑定数据
this.ddlgoodswtype.Items.Add(new ListItem("--请选择--", "-1"));
this.ddlgoodswtype.DataSource = BLL.Goods_tab.Selectgoodswtype();
this.ddlgoodswtype.DataTextField = "goodswtypeName"; //文本显示的内容
this.ddlgoodswtype.DataValueField = "goodswtypeID"; //文本值
this.ddlgoodswtype.DataBind();
DropDownList 联动,设置属性 AutoPostBack=“True”
在第一个DropDownList SelectedIndexChanged事件里
string goodswtypeID = this.ddlgoodswtype.SelectedValue.ToString();
Cookie用法
七天免登录,登录按钮点击事件部分
HttpCookie cookie = new HttpCookie("login");
cookie.Values["adminName"] = txtname.Text.Trim();
cookie.Values["amdinPwd"] = txtpwd.Text.Trim();
cookie.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(cookie);
窗体加载部分
if (Request.Cookies["login"] != null)
{
this.txtname.Text = Request.Cookies["login"]["adminName"].ToString();
this.txtpwd.Attributes["value"] = Request.Cookies["login"]["amdinPwd"];
this.chboxlogin.Checked = true;
}
Session用法
在一个项目中的所有页面都可以用(当我的项目关闭时,Session值清空)
定义Session并赋值
Session["adminNameSession"] = name;
判断并获取Session值
if (Session["adminNameSession"] != null)
{
this.labName.Text = Session["adminNameSession"].ToString();
}
数据绑定修改日期格式
<asp:Label ID="labshenr" runat="server" Text='<%#Bind("userBirth","{0:yyyy-MM-dd}") %>'></asp:Label>
遍历页面所有CheckBox控件
foreach (Control ct in Form.Controls) //遍历页面所有CheckBox控件
{
if (ct.GetType().ToString().Equals("System.Web.UI.WebControls.CheckBox"))
{
CheckBox cb = (CheckBox)ct;
cb.Checked = check.Checked;
}
}
找控件
TextBox txtBir = this.Birth.FindControl("txtbur") as TextBox;//在Birth里面找id为txtbur的控件
GridView用法
this.Gvinfor.DataSource = BLL.StuInfoBLL.BindData();//数据绑定
this.Gvinfor.DataBind(); //显示数据
GridView 行内添加按钮
<asp:ButtonField ButtonType="Button" Text="编辑" CommandName="gvupdate" /> //CommandName="gvupdate" 个按钮取名字
DataKeyName 属性 将字段绑定到GridView 每行上,操作某一行时可以获取当行绑定的字段值
点击一行的某个按钮
protected void Gvinfor_RowCommand(object sender, GridViewCommandEventArgs e)
{
//判断点击是否是删除按钮
if (e.CommandName == "gvdel")
{
//获取当前要删除行的索引
int index = Convert.ToInt32(e.CommandArgument);
//根据当前操作的行索引找到DataKeyName属性里绑定字段的值
int id = Convert.ToInt32(Gvinfor.DataKeys[index].Value);
if (BLL.StuInfoBLL.Delinfor(id))
{
Response.Write("<script>alert('删除成功')</script>");
this.Gvinfor.DataSource = BLL.StuInfoBLL.BindData();
this.Gvinfor.DataBind();
}
else
{
Response.Write("<script>alert('删除失败')</script>");
}
}
}
获取当前行是索引
int index = Convert.ToInt32(e.CommandArgument);
根据当前操作行的索引找到DataKeyNames属性里面绑定字段的值
int ID = Convert.ToInt32(gvStu.DataKeys[index].Value);
模板列
<asp:TemplateField HeaderText="终点站">
<%--编辑模版列状态--%>
<EditItemTemplate>
<%--<asp:CheckBox ID="ddl" runat="server" Text='<%# Bind("End_station") %>'></asp:CheckBox>--%>
<%--Eval单向绑定只能读取数据 Bind 双向绑定既可以读取数据也可以修改数据--%>
<asp:TextBox ID="txtStation" runat="server" Text='<%# Bind("End_station") %>'></asp:TextBox>
</EditItemTemplate>
<%--显示模版列状态--%>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("End_station") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
光棒效果
protected void gdvDetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
//製作gridview光棒效果
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#AAAAAA';");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor;");
}
}
日期格式化显示
<asp:TemplateField HeaderText="创建日期">
<ItemTemplate>
<asp:Label ID="labrq" runat="server" Text='<%#Bind("creatDate","{0:yyyy-MM-dd}") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="10%" />
</asp:TemplateField>
嵌套Repeater
在外层Repeater每项数据绑定后事件里通过找控件 找到里层Repeater。
/// <summary>
/// 每项数据绑定后事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void repgoodswtype_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Label labId = e.Item.FindControl("labgoodswtypeID") as Label; //外层Repeater绑定的数据
Repeater repgoodstype = e.Item.FindControl("repgoodstype") as Repeater; //里层Repeater
repgoodstype.DataSource = BLL.Goods_tab.SelectgoodstypeByid(labId.Text.ToString());
repgoodstype.DataBind();
}
用户控件
用户控件时一种自定义的组合控件,封装独立的功能 后缀名 .ascx 实现代码的重用
新建Web窗体用户控件 .ascx ------ 在用户控件里面写内容 ------直接拖拽使用
生成:(在页面上方)
<%@ Register Src="~/test1/upadte.ascx" TagPrefix="uc1" TagName="upadte" %>
页面中
<uc1:upadte runat="server" id="upadte" />
Src :路径(指向控件的资源文件)
一般处理程序 .ashx
- ProcessRequest() 方法:是Http请求的最终处理方式
- HttpContext:和本次请求相关对象的一个上下文对象
- ContentType:输出流(表示告诉浏览器请求的是什么类型的文件) text/html 浏览器标签 text/plain 文本 image/jpeg 图片
- End() 将当前所有缓冲的输出发送到客户端,停止该页的执行
- MapPath() 将虚拟路径转换为磁盘上的绝对路径,操作项目中的文件使用
- OutputStream:输出流
存放一张照片——获取图片名称——提交到Handler(url ? 传值)
Handler:接过来的图片名称存放到虚拟路径——将虚拟路径转化为磁盘上的绝对路径——将图片转成画布——在画布写文字(打上文字水印)——释放了画布)——将图片存入到输出流——释放资源——结束响应
HttpHandler 上传图片
前端页面
<form action="test2.ashx" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="filew"/>
<input type="submit" name="sub" value="上传图片"/>
</div>
</form>
一般处理程序代码
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
//context.Response.Write("Hello World");
//获取上传的文件
HttpPostedFile file = context.Request.Files[0];
//
if (file.ContentLength > 0)
{
//对上传的文件进行检查(是否是需要的图片类型)
//(判断后缀名)获取上传文件的名称(包含的后缀名)
string filename = Path.GetFileName(file.FileName);
//获取上传文件的后缀名.jpg
string fileExit = Path.GetExtension(filename);
//判断后缀名是否为.jpg或者.png
if(fileExit==".jpg" || fileExit == ".png")
{
//对上传文件进行重名名
string newfilename = Guid.NewGuid().ToString();
//将上传的文件放在目录下
string dirupload = "/img/newimg/";
//创建文件夹(判断磁盘上是否有现有的路径,没有就创建一个)
if(!Directory.Exists(context.Request.MapPath(dirupload)))
{
Directory.CreateDirectory(context.Request.MapPath(dirupload));
}
//找到文件的完整路径
string allDir = dirupload + newfilename + fileExit;
//保存路径
file.SaveAs(context.Request.MapPath(allDir));
//创建图片水印
//创建一个Image
using (Image tp = Image.FromFile(context.Request.MapPath(allDir)))
{
//创建画布
using (Bitmap map = new Bitmap(tp.Width, tp.Height))
{
//创建画笔
using (Graphics grap = Graphics.FromImage(map))
{
//在指定的位置上
grap.DrawImage(tp,0,0,tp.Width,tp.Height);
//创建字体
Font ft= new Font("楷体", 18);
//指定绘制的文本
grap.DrawString("新鲜美淘网", ft, Brushes.Red,new Point(map.Width-150,map.Height- ft.Height));
string WYImagename = "WY" + Guid.NewGuid().ToString();
map.Save(context.Request.MapPath("/img/newimg/"+ WYImagename+ fileExit),ImageFormat.Jpeg);
//输出
context.Response.Write("<html><body><img src='/img/newimg/"+ WYImagename + fileExit + "' /></body></html>");
}
}
}
}
}
}
成员资格管理
一、身份验证
身份验证:就是从用户获取名称和密码标识凭证并根据某些机制验证这些凭据的过程,如果凭据有效,说明该凭据被视为通过身份验证的标识,一旦通过身份验证,就可以确定是否能访问给定的资源
二、ASP.NET安全模式
- windows身份验证(内联网非常有效)通过IIS配置,默认值
- Passport身份验证:微软提供收费的证书,国内使用比较少
- Forms身份验证:实际并发中最普遍的,在网站内部提供特定的cookie,提供FormsHuthentication类用于提供身份验证的服务提供一个标识用户身份的cookie)
- None:在IIS中不做太多限制,该请求应用于任何附加的身份验证,当要实现自定义的身份验证方案或者只是想匿名身份验证并且想获得尽苛能高的性能将级别时,通常使用它
- Federate:(谷歌提供)单点登录标准
语法:
<authentication mode="[windows | Passport4Forms | None | Federate]"></authentication>
三、windows身份验证
使用iis所支持的任何一种机制,依赖于Internet信息服务提供已通过身份验证的用户
<authentication mode="windows"/>
<identity impersonate="true"/>
Passport身份验证
是指Microsoft提供的集中身份验证服务,用于为成员站点提供单一登录和核心的配置文件服务,不再需要登录以访问新的加密资源或者站点,使我们的站点与Passport身份验证和授权兼容
Forms身份验证
通常是指以下系统,使用HTTP客户端重定向功能将未经验证的请求重定向到某个HTML表单,如果应用程序在通过HTMI表单登录时需要搜集自己的用户凭据,就会使用它。如果应用程序验证该请求,哪呢系统将会发出一个包含凭据的cookie以重新获取标识
四、基于窗体的授权模式
用户身份验证的信息通过form标签进行提交 form常用的属性:
- name:给提交cookie命名
- protection:验证cookie的保护级别all(默认,加密+验证)None(不加密不验证)
- Encryption (cookie加密但是不验证)Validation(验证但是不加密)
- path:制定cookie存储的路径,默认设置
五、拒绝匿名用户
<authorization>
<deny users="?"
</authorization>
- authorization:授权
- deny:拒绝
- allow:允许
- ?:引用匿名标识
- *:引用所有标识
六、在配置文件中创建一个用户在登录的时候进行验证
using System.Web.Security:
//对照在应用程序存储在配置文件中的凭据来验证用户名和密码(bool)
FormsAuthentication.Authenticate(用户名.密码)
//经过身份验证后重定向最初请求的路径(配置文件中defaultUrl路径)
FormsAuthentication.RedirectFromLoginPage(username,false)
//在配置文件:
<authentication mode="Forms">
<forms nane ="Users" loginUrl="Index.aspx"defaultUrl ="Main.aspx">
<credentials passwordFormat "Clear">
<user name="admin" password="123"/>
<user name="Test" password="123"/>
</ cradentiais>
</forms>
<authent ication>
Ajax
$.ajax({
url: "userCars.ashx", //请求地址
type: "get", //请求方式
data: { mss: "mssjian", goodid: goodid }, //传递参数
success: function (msg) { //msg返回的内容
if (msg == "减少成功")
{
}
},
})