结合项目二内容 本章内容运用到ASP.NET里面”Web用户控件“与“水印”功能
一、结合第二章内容已经实现产品详细,本章内容主要运用“ASP.NETWeb用户控件”来实现”查找产品“,
首先“BraSys”项目里面新建一个文件夹名叫“FindControl”,在“FindControl文件夹”添加新项,选择“Web用户控件”名为“BraControl.ascx”
如图所示:
二、添加完成后,在“设计”拖进“TextBox控件”和“LinkButton控件”分别来时实现客户”输入“和“提交”功能并添加适合样式
如图所示:
代码示例:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="BraControl.ascx.cs" Inherits="FindControl_BraControl" %> <style type="text/css"> span { margin-left:40%; line-height:30px; font-weight:bold; } </style> <span>请输入关键字<asp:TextBox Width="150px" Height="20px" ID="txtKey" runat="server"></asp:TextBox></span> <asp:LinkButton ID="lkbFind" runat="server" Font-Bold="True" Font-Strikeout="False" Font-Underline="False">查 找</asp:LinkButton>
三、完成后,来到“BraClothList.aspx窗体”找到合适位置,把““BraControl.ascx”Web用户控件”拖进去
如图所示:
四、拖进后,添加一个“Web窗体”主要实现”查找到产品“,改名为“BraFind.aspx”,选择“母版”,
拖进一个“DataList控件”编辑前台代码,接着也拖进“BraControl.ascxWeb用户控件”
1、如图所示(DataList前台代码):
2、如图所示(Web用户控件)
代码示例
<%@ Page Title="" Language="C#" MasterPageFile="~/BrasServer/Bratheme.master" AutoEventWireup="true" CodeFile="BraFind.aspx.cs" Inherits="BrasServer_BraFind" %> <%@ Register Src="~/FindControl/BraControl.ascx" TagPrefix="uc1" TagName="BraControl" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <style type="text/css"> .DataListdiv { margin-left:20%; } </style> <fieldset> <legend>产品查找</legend> <div> <uc1:BraControl runat="server" ID="BraControl" /> </div> <div class="DataListdiv"> <asp:DataList ID="BraProductList" runat="server"> <ItemTemplate> <table style="100%;height:180px;"> <tr> <td rowspan="5"> <asp:Image ID="Image1" runat="server" Width="165px" Height="175px" BorderWidth="5" ImageUrl='<%#Eval("ImgSrc","~/{0}") %>'/> </td> <td> <a href='BarDetail.aspx?ProductId=<%#Eval("ProductId") %>' class="a1"> <%#Eval("ProductName") %></a> </td> </tr> <tr> <td class="a3">价格:<%#Eval("Price","{0:F1}") %></td> </tr> <tr> <td class="a3">日期:<%#Eval("PublishDate","{0:yyyy-MM-dd}") %>></td> </tr> <tr> <td style="270px"> <span class="a2"> <a href='ShowCart.aspx?ProductId=<%#Eval("ProductId") %>'> <img src="../images/btn_new.jpg" style="height:32px;100px;" />添加购物车</a> </span> </td> </tr> <tr> <td colspan="3" style="border-bottom:2px solid red;height:5px;"> </td> </tr> </table> </ItemTemplate> </asp:DataList> </div> </fieldset> </asp:Content>
五、运用数据库写出“通过关键字查询数据”方法,通过”三层架构“调用
1、如图所示(SQL方法语句)
代码示例:
--通过关键字来查找数据 create proc Xyy_BarProductByKey @Key varchar(200) as begin select ProductId,ProductName,Price,PublishDate,ImgSrc from Bars where ProductName like '%'+@Key+'%' end
2、如图所示:(数据访问层)
代码示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DBUtility; using Models; using System.Data.SqlClient; namespace DAL { public class BarsService { //日期排序 public List<Bars> Xyy_BarGetpageList(string key, int startindex, int endidenx, string orderkey) { List<Bars> lst = new List<Bars>(); SqlParameter[] param = new SqlParameter[] { new SqlParameter("@Key",key), new SqlParameter("@StartIdenx",startindex), new SqlParameter("@EndIdenx",endidenx), new SqlParameter("@OrderKey",orderkey) }; using (SqlDataReader dr = SqlHelper.ExecuteReader("Xyy_BarGetpageList", param)) { while (dr.Read()) { lst.Add(new Bars { ProductId = Convert.ToInt32(dr["ProductId"]), ProductName = Convert.ToString(dr["ProductName"]), Price = Convert.ToInt32(dr["Price"]), PublishDate = dr["PublishDate"] == DBNull.Value ? DateTime.Now : Convert.ToDateTime(dr["PublishDate"]), ImgSrc = dr["ImgSrc"].ToString() }); } } return lst; } //分类选中 public int XYY_Bars_Count_Key(string cateid) { SqlParameter[] param = new SqlParameter[] { new SqlParameter("@categoryid",cateid) }; object obj = SqlHelper.ExecuteScalar("XYY_Product_Count_Key", param); if (obj != null) { return Convert.ToInt32(obj); } else { return 0; } } //获取产品详细 public Bars Xyy_ProductGetModel(string productId) { SqlParameter[] param = new SqlParameter[] { new SqlParameter("@ProductId",productId) }; Bars models = null; using (SqlDataReader dr = SqlHelper.ExecuteReader("Xyy_ProductGetModel", param)) { if (dr.Read()) { models = new Bars(); models.ProductId = Convert.ToInt32(dr["ProductId"]); models.ProductName = Convert.ToString(dr["ProductName"]); models.Brand = Convert.ToString(dr["Brand"]); models.CategoryId = dr["CategoryId"] == DBNull.Value ? 0 : Convert.ToInt32(dr["CategoryId"]); models.Price = Convert.ToInt32(dr["Price"]); models.nContent = Convert.ToString(dr["nContent"]); models.ImgSrc = Convert.ToString(dr["ImgSrc"]); models.PublishDate = dr["PublishDate"] == DBNull.Value ? DateTime.Now : Convert.ToDateTime(dr["PublishDate"]); models.Area = Convert.ToString(dr["Area"]); models.Fresh = Convert.ToString(dr["Fresh"]); models.CliclTime = Convert.ToInt32(dr["CliclTime"]); models.Vis = Convert.ToBoolean(dr["Vis"]); } } return models; } //通过关键字查找数据 public List<Bars> Xyy_BraProductByKey(string Key) { List<Bars> lst = new List<Bars>(); SqlParameter[] param = new SqlParameter[] { new SqlParameter("@Key",Key) }; Bars model = null; using (SqlDataReader dr = SqlHelper.ExecuteReader("Xyy_BarProductByKey", param)) { while(dr.Read()) { model = new Bars(); model.ProductId = Convert.ToInt32(dr["ProductId"]); model.ProductName = Convert.ToString(dr["ProductName"]); model.Price = Convert.ToInt32(dr["Price"]); model.PublishDate = dr["PublishDate"] == DBNull.Value ? DateTime.Now : Convert.ToDateTime(dr["PublishDate"]); model.ImgSrc = Convert.ToString(dr["ImgSrc"]); lst.Add(model); } } return lst; } } }
3、如图所示(逻辑层)
代码示例
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Models; using DAL; namespace BLL { public class BarManager { BarsService dal = new BarsService(); //日期 public List<Bars> Xyy_BarGetpageList(string key, int startindex, int endidenx, string orderkey) { return dal.Xyy_BarGetpageList(key, startindex, endidenx, orderkey); } //分类选中 public int XYY_Bars_Count_Key(string cateid) { return dal.XYY_Bars_Count_Key(cateid); } //获取产品详细 public Bars Xyy_ProductGetModel(string productId) { return dal.Xyy_ProductGetModel(productId); } //通过关键字查找数据 public List<Bars> Xyy_BraProductByKey(string Key) { return dal.Xyy_BraProductByKey(Key); } } }
六、在调用“表示层”时,先在”BraControl.ascxWed用户控件“编辑"委托事件"
如图所示:
代码示例:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class FindControl_BraControl : System.Web.UI.UserControl { //定义委托 public delegate void LkbCllick(string key); public event LkbCllick OnLkbClick; protected void Page_Load(object sender, EventArgs e) { } //定义属性 public string Text { get { return txtKey.Text; } set { txtKey.Text = value; } } //查找事件 protected void lkbFind_Click(object sender, EventArgs e) { if (OnLkbClick != null) { string key = txtKey.Text; OnLkbClick(key); } } }
七、在“BraClothList.aspx窗体”和“BraFind.aspx窗体”调用”触发事件“
1、如图所示(BraClothList.aspx窗体):
代码示例
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Models; using BLL; public partial class BrasServer_BraClothList : System.Web.UI.Page { CategoriesManager cll = new CategoriesManager(); BarManager bll = new BarManager(); private int pageSize = 4; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //初始化 pageIndex = 0; OrderKey = "Price"; LoadCates(); //设置第一行选中 lbCates.SelectedIndex = 1; lbCates_SelectedIndexChanged(null, null); } //注册用户控件事件 BraControl.OnLkbClick += new FindControl_BraControl.LkbCllick(Lkb_Click); } //触发事件 private void Lkb_Click(string key) { Response.Redirect("~/BrasServer/BraFind.aspx?Key=" + key); } //种类 private void LoadCates() { lbCates.DataValueField = "CateId"; lbCates.DataTextField = "Name"; lbCates.DataSource = cll.Xyy_Categories_GetList(); lbCates.DataBind(); } //加载数据 private void LoadData() { string key = ""; if (lbCates.SelectedValue != "0") { key = " where CategoryId=" + lbCates.SelectedValue + " and Vis=1"; } repClothList.DataSource = bll.Xyy_BarGetpageList(key, pageSize * pageIndex + 1, pageSize * (pageIndex + 1), OrderKey); repClothList.DataBind(); if (repClothList.Items.Count > 0) { //显示分页 lblPage.Text = ViewState["msg"].ToString() + ",当前第:" + (pageIndex + 1).ToString() + "页"; } else { lblPage.Text = ViewState["msg"].ToString() + ",当前第0页"; } SetButtonState(); } //设置按钮状态 private void SetButtonState() { //设置所有按钮有效 lkbprev.Enabled = true; lkbNext.Enabled = true; //设置无效按钮 if (pageIndex == 0) { lkbprev.Enabled = false; } if (pageIndex + 1 == PageCount || PageCount == 0) { lkbNext.Enabled = false; } } //页面索引 private int pageIndex { get {return (int)ViewState["pageindex"]; } set { ViewState["pageindex"] = value; } } //排序索引 private string OrderKey { get { return ViewState["order"].ToString(); } set { ViewState["order"] = value; } } //总页数 private int PageCount { get { return (int)ViewState["pagecount"]; } set { ViewState["pagecount"] = value; } } //分类选中事件 protected void lbCates_SelectedIndexChanged(object sender, EventArgs e) { pageIndex = 0; int count = bll.XYY_Bars_Count_Key(lbCates.SelectedValue); PageCount = (int)Math.Ceiling(count * 1.0 / pageSize); //总页数 ViewState["msg"] = "总有:" + count.ToString() + "记录,共有:" + PageCount.ToString() + "页"; LoadData(); } //上一页 protected void lkbprev_Click(object sender, EventArgs e) { pageIndex--; LoadData(); } //下一页 protected void lkbNext_Click(object sender, EventArgs e) { pageIndex++; LoadData(); } }
2、如图所示(BraFind.aspx窗体)
代码示例
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Models; using BLL; public partial class ClothesFind : System.Web.UI.Page { ProductManager bll = new ProductManager(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { LoadData(); if (Request.QueryString["Key"] != null) { FindControl.Text = Request.QueryString["Key"]; } } //注册用户控件事件 FindControl.OnLkbClick += new Controls_FindControl.LkbCllick(Lkb_Click); } //触发事件 private void Lkb_Click(string key) { ProductList.DataSource = bll.GetListByKey(key); ProductList.DataBind(); } //加载数据 private void LoadData() { string Key = ""; if (Request.QueryString["Key"] != null) Key=Request.QueryString["Key"]; ProductList.DataSource = bll.GetListByKey(Key); ProductList.DataBind(); } }
3、如图所示(绑定按钮事件)
八、完成”Web用户控件“功能后,实现“水印”,在“BraSys”项目添加一个文件名为"Handles",
在"Handles"添加"一般处理程序"名为"ImgHandler.ashx"
如图所示:
九、在”ImgHandler.ashx“一般处理程序编辑”水印“方法
如图所示:
代码示例;
<%@ WebHandler Language="C#" Class="ImgHandler" %> using System; using System.Web; using System.Drawing; using Models; using BLL; using System.Drawing.Drawing2D; public class ImgHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); //获取产品Id string id = context.Request.QueryString["Id"]; Bars bs = new BarManager().Xyy_ProductGetModel(id); context.Response.ContentType = "image/jpeg"; //转成物理路径 string path = context.Server.MapPath("~/" + bs.ImgSrc); //把图片路径转成图片对象 Image img = Image.FromFile(path); //导入画板 Graphics g = Graphics.FromImage(img); Matrix matrix = new Matrix(); //旋转45度 matrix.Rotate(45); g.Transform = matrix; g.DrawLine(Pens.Blue, 0, 0, 0, 0); //定义刷子 SolidBrush brusb = new SolidBrush(Color.Red); //在画布上写入文字 g.DrawString("羊羊羊",new Font("宋体",50f),brusb,150,-10); //输出 img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); context.Response.End(); } public bool IsReusable { get { return false; } } }
十、来“BrasServer/BraFind.aspx”窗体前台代码绑定图片路径,注释点之前的
如图所示:
代码示例
<%@ Page Title="" Language="C#" MasterPageFile="~/BrasServer/Bratheme.master" AutoEventWireup="true" CodeFile="BraFind.aspx.cs" Inherits="BrasServer_BraFind" %> <%@ Register Src="~/FindControl/BraControl.ascx" TagPrefix="uc1" TagName="BraControl" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <style type="text/css"> .DataListdiv { margin-left:20%; } </style><fieldset> <legend>产品查找</legend> <div> <uc1:BraControl runat="server" ID="BraControl" /> </div> <div class="DataListdiv"> <asp:DataList ID="BraProductList" runat="server" RepeatColumns="2"> <ItemTemplate> <table style=" 100%;"> <tr> <td rowspan="5"> <%-- <asp:Image ID="Image1" runat="server" Width="165px" Height="175px" BorderWidth="5" ImageUrl='<%#Eval("ImgSrc","~/{0}") %>' />--%> <asp:Image ID="Image1" runat="server" Width="165px" Height="175px" BorderWidth="5" ImageUrl='<%#Eval("ProductId","~/Handles/ImgHandler.ashx?Id={0}") %>' /> </td> <td style="text-align:center"> <a href='BarDetail.aspx?ProductId=<%#Eval("ProductId") %>' class="a1"> <%#Eval("ProductName") %></a> </td> </tr> <tr> <td class="a3">价格:<%#Eval("Price","{0:F1}") %></td> </tr> <tr> <td class="a3">日期:<%#Eval("PublishDate","{0:yyyy-MM-dd}") %>></td> </tr> <tr> <td style=" 270px"> <span class="a2"> <a href='ShowCart.aspx?ProductId=<%#Eval("ProductId") %>'> <img src="../images/btn_new.jpg" style="height: 32px; 100px;" />添加购物车</a> </span> </td> </tr> <tr> <td colspan="3" style="border-bottom: 2px solid red; height: 5px;"> </td> </tr> </table> </ItemTemplate> </asp:DataList> </div> </fieldset> </asp:Content>
十一、最后编辑“Web.config”文件就可以了
如图所示:
代码示例:
<?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> <!--印刷--> <system.webServer> <handlers> <add name="Handles" verb="*" path="ImgSrc/*.jpg" type="ImgConver"/> </handlers> </system.webServer> <connectionStrings> <add name="ConnectString" connectionString="Data Source=.;Initial Catalog=BarsSys;User ID=sa;Pwd=sa;"/> </connectionStrings> </configuration>
运行效果: