ASP课堂--期末复习
1、 建立网站,以班级+序号+姓名为名字(如“软件工程1班1好张三”)来建立网站。建立数据库test,其中包含stu_info表和goods_info表,stu_info表结构:(Done)
stu_name varchar(20)
stu_pwd varchar(20)
在stu_info表中插入一条记录(”zhang”,”zhang”)
goods_info表结构:
goods_id int
goods_name varchar(50)
goods_price float
goods_date varchar(20)
goods_images varchar(100)
2、 新建login.aspx页面,要求在此页面中用户输入用户名和密码,当用户单击“登录“按钮时,判断用户的输入与stu_info表中的数据是否符合,如果不符合,弹出对话框提示”用户名或密码错误“,如果用户输入正确,将用户的用户名保存到Session,并跳转到goodsadmin.aspx页面。(Done)
using System; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Collections.Generic; using System.Data; public partial class login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void LoginBtn_Click(object sender, EventArgs e) { //连接字符串 string connStr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\My Documents\\Test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; //获取用户的输入 string username = tbUserName.Text; string password = tbPassword.Text; //sql语句,用来查询 string sqlStr = "select * from stu_info where stu_name='" + username +"'"; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); //打开数据库连接 using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sqlStr; DataSet ds = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(ds); DataTable table = ds.Tables[0]; if (table.Rows.Count <= 0) { Response.Write(@"<script>alert('用户名不存在!');</script>"); return; } else { DataRow rows = table.Rows[0]; string dbpassword = (string)rows["stu_pwd"]; if (dbpassword == password) { //将用户名保存到Session Session["username"] = (string)rows["stu_name"]; Response.Redirect("~/goodsAdmin.aspx"); } else { Response.Write(@"<script>alert('密码错误!');</script>"); return; } } } } } }
3、 新建goodsinsert.aspx页面,首先判断用户是否已经登录,如果没有登录则跳转到login.aspx页面。在此页码中,要求用户输入商品的名称、价格、上传日期和图片,单击“插入数据“按钮时,将图片上传到网站的images文件夹中(请先建立此文件夹),同时将商品的名称、价格、上传日期和图片在网站的相对路径(如~/images/1.jpg)保存到goods_info表中。(Done)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; public partial class goodsInsert : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnInsert_Click(object sender, EventArgs e) { string savePath = Server.MapPath("~/images/"); if (FileUpload1.HasFile) { String filename = FileUpload1.FileName; savePath += filename; FileUpload1.SaveAs(savePath); } string goodsname = tbGoodsName.Text.ToString(); string goodsprice = tbGoodsPrice.Text.ToString(); string goodsdate = tbGoodsDate.Text.ToString(); string connStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\My Documents\Test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; string sqlStr = @"Insert into goods_info(goods_name, goods_price, goods_date, goods_images) values('"; sqlStr += goodsname + "'," + goodsprice + ",'" + goodsdate + "','" + savePath + "')"; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sqlStr; cmd.ExecuteNonQuery(); //执行sql语句,插入数据 } } Response.Write("<script>alert('插入成功!!!');</script>"); } }
4、 新建goodsadmin页面,首先判断用户是否已经登录,如果没有登录则跳转到login.aspx页面。在此页码中,要求用gridview显示所有的商品信息,并在gridview中为商品添加“编辑“和”删除“功能。(Done)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; public partial class goodsAdmin : System.Web.UI.Page { //连接字符串 string connStr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\My Documents\\Test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; DataSet ds; protected void Page_Load(object sender, EventArgs e) { //如果用户没有登陆 if (Session["username"] == null) { Response.Redirect("~/login.aspx"); } else { bind(); } } /// <summary> /// 数据绑定到gridView /// </summary> public void bind() { string sqlStr = "select * from goods_info"; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sqlStr; SqlDataAdapter adapter = new SqlDataAdapter(cmd); ds = new DataSet(); adapter.Fill(ds); } } GridView1.DataSource = ds; GridView1.DataBind(); } /// <summary> /// 为gridview 添加编辑功能 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { //设计要编辑的行 GridView1.EditIndex = e.NewEditIndex; bind(); } /// <summary> /// 删除操作 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { string goods_name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0])).Text.ToString(); string sql = "delete from goods_info where goods_name = '" + goods_name + "'"; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.ExecuteNonQuery(); } } GridView1.EditIndex = -1; bind(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; bind(); } }
5、 在网站中添加”App_Code”文件夹,在其中添加一个类,在此类中分别定义可以实现建立数据库连接、执行sql查询语句和执行sql更新语句的方法。(Done)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; using System.Data; /// <summary> ///SqlHelp 的摘要说明 /// </summary> public class SqlHelper { //连接字符串 private static string connStr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\My Documents\\Test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; private SqlConnection conn = null; private SqlCommand cmd = null; private SqlDataReader dataReader = null; private DataSet ds = null; /// <summary> /// 获得数据库对象 /// </summary> /// <returns></returns> public SqlConnection getConnection() { conn = new SqlConnection(connStr); return conn; } /// <summary> /// 返回查询结果 /// </summary> /// <param name="sql"></param> /// <returns></returns> public SqlDataReader executeNonQuery(string sql) { if (conn == null) { conn = getConnection(); } cmd = new SqlCommand(sql, conn); conn.Open(); return cmd.ExecuteReader(); } /// <summary> /// 更新操作 /// </summary> /// <param name="sql"></param> /// <returns></returns> public int update(string sql) { if (conn == null) { conn = getConnection(); } cmd = new SqlCommand(sql, conn); conn.Open(); int i = cmd.ExecuteNonQuery(); return i; } /// <summary> /// 给定sql语句,返回结构集 /// </summary> /// <param name="sql"></param> /// <returns></returns> public DataSet executeDataSet(string sql) { if (conn == null) { conn = getConnection(); } cmd = new SqlCommand(sql, conn); conn.Open(); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); return ds; } /// <summary> /// 关闭数据库连接 /// </summary> public void close() { if (conn != null) { conn.Close(); } } }
6、 新建index.aspx页面,在此页面中通过datalist控件来显示goods_info表中每个商品的商品的名称、价格、上传日期和图片,并在每个商品的下面添加一个按钮,当单击按钮时,弹出对话框显示该按钮被单击的次数。(Done)
界面代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="goodsnum" %> <!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> <style type="text/css"> .style1 { width: 100%; } .style2 { width: 110px; } .style3 { width: 100px; } </style> </head> <body> <form id="form1" runat="server"> <div> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="D:\My Documents\Test.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM [goods_info]"> </asp:SqlDataSource> <asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" RepeatColumns="3" RepeatDirection="Horizontal" onitemcommand="DataList1_ItemCommand" > <ItemTemplate> <table class="style1"> <tr> <td align="center" colspan="2"> <asp:Image ID="Image1" runat="server" Height="108px" ImageUrl='<%# Eval("goods_images") %>' Width="227px" /> </td> </tr> <tr> <td align="right" class="style3"> 名称:</td> <td> <asp:Label ID="Label1" runat="server" Text='<%# Eval("goods_name") %>'></asp:Label> </td> </tr> <tr> <td align="right" class="style3"> 价格:</td> <td> <asp:Label ID="Label2" runat="server" Text='<%# Eval("goods_price") %>'></asp:Label> </td> </tr> <tr> <td align="right" class="style3"> 上传日期:</td> <td> <asp:Label ID="Label3" runat="server" Text='<%# Eval("goods_date") %>'></asp:Label> </td> </tr> <tr> <td align="center" colspan="2"> <asp:Button ID="Button1" runat="server" Text="显示点击次数" CommandArgument='<%# Eval("goods_id") %>' /> </td> </tr> </table> </ItemTemplate> </asp:DataList> </div> </form> </body> </html>
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e) { string id = e.CommandArgument.ToString(); Hashtable ht; if (Session["count"] == null) { ht = new Hashtable(); ht.Add(id, 1); Session["count"] = ht; } else { ht = (Hashtable)Session["count"]; if (ht.Contains(id)) { int count = int.Parse(ht[id].ToString()); ht[id] = count + 1; Session["count"] = ht; Response.Write("<script>alert('" + (count + 1) + "');</script>"); } else { ht.Add(id, 1); Session["count"] = ht; } }
7、 新建goodsnum.aspx页面,在此页面的Page_Load事件中,首先定义一个DataTable,分别包含三列
列名 类型
name string
price float
num int
并编程在此表中添加三条记录。通过GridView显示此表中的数据。(Done)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections; using System.Data; public partial class index : System.Web.UI.Page { private DataTable dt; protected void Page_Load(object sender, EventArgs e) { /**定义一个DataTable,分别包含三列 列名 类型 name string price float num int **/ dt = new DataTable(); DataColumn col = new DataColumn(); col.ColumnName = "name"; col.DataType = System.Type.GetType("System.String"); dt.Columns.Add(col); col = new DataColumn(); col.ColumnName = "price"; col.DataType = System.Type.GetType("System.Single"); dt.Columns.Add(col); col = new DataColumn(); col.ColumnName = "num"; col.DataType = System.Type.GetType("System.Int32"); dt.Columns.Add(col); Bind(); } /// <summary> /// 通过编程来实现往DataTable里添加数据,并绑定到GridView当中 /// </summary> public void Bind() { DataRow row = dt.NewRow(); row["name"] = "zhangsan"; row["price"] = 11.0f; row["num"] = 10; dt.Rows.Add(row); row = dt.NewRow(); row["name"] = "lishi"; row["price"] = 12.0f; row["num"] = 50; dt.Rows.Add(row); row = dt.NewRow(); row["name"] = "wangwu"; row["price"] = 13.0f; row["num"] = 100; dt.Rows.Add(row); gridView.DataSource = dt.DefaultView; gridView.DataBind(); } }
8、建立一个Web服务,要求根据商品名称,通过查询goods_info表返回商品的价格。
/// <summary> /// 定义一个服务方法,根据商品名称,通过查询goods_info表返回商品的价格。 /// </summary> /// <param name="goodsname"></param> /// <returns></returns> [WebMethod] public double getPrice(string goodsname) { string connStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\My Documents\Test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; string sqlStr = "select * from goods_info where goods_name = '" + goodsname + "'"; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sqlStr; DataSet ds = new DataSet(); SqlDataAdapter sda = new SqlDataAdapter(cmd); sda.Fill(ds); DataTable dt = ds.Tables[0]; DataRow rows = dt.Rows[0]; double price = (double)rows["goods_price"]; return price; } } }