【一】:添加商品页面
1:建立product_add.aspx页面。
界面设计如下:
为图片预览添加一个默认图片。
aspx代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="product_add.aspx.cs" Inherits="Web.admin.product_add" %> <!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> </head> <body> <form id="form1" runat="server"> <h1>添加商品</h1> <br /> 商品名称:<asp:TextBox ID="txtname" runat="server" Width="206px"></asp:TextBox> <br /> <br /> 商品图片:<asp:FileUpload ID="fuimg" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="上传" /> <br /> <br /> 图片预览:<br /> <asp:Image ID="imgYL" runat="server" ImageUrl="~/upload/none.jpg" /> <br /> 市场价:<asp:TextBox ID="txtmarket" runat="server"></asp:TextBox> 会员价:<asp:TextBox ID="txtmember" runat="server"></asp:TextBox> VIP价:<asp:TextBox ID="txtvip" runat="server"></asp:TextBox> <br /> <br /> 商品状态:<asp:TextBox ID="txtstate" runat="server"></asp:TextBox> <br /> <br /> 商品规格:<asp:TextBox ID="txtnorm" runat="server"></asp:TextBox> <br /> <br /> 商品单位:<asp:TextBox ID="txtdw" runat="server"></asp:TextBox> <br /> <br /> 所属分类:<asp:DropDownList ID="ddl" runat="server"> </asp:DropDownList> <br /> <br /> <asp:CheckBoxList ID="cbl" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow"> <asp:ListItem>特价商品</asp:ListItem> <asp:ListItem>新品上市</asp:ListItem> <asp:ListItem>VIP特惠</asp:ListItem> </asp:CheckBoxList> <br /> <br /> 商品描述:<br /> <asp:TextBox ID="txtdesc" runat="server" Height="132px" Width="537px"></asp:TextBox> <br /> <asp:Button ID="btnadd" runat="server" Text="添加商品" /> </form> </body> </html>
①:使用Linq技术为下拉列表框绑定数据
////原来的绑定方式 //List<MyShop.Model.Categroy> list = new MyShop.DAL.CategroyDAO().GetListArray(""); //ddl.DataTextField = "caname"; //ddl.DataValueField = "id"; //ddl.DataSource = list; //ddl.DataBind(); //使用Linq使下列表显示二级分类 List<MyShop.Model.Categroy> list = new MyShop.DAL.CategroyDAO().GetListArray(""); var first = list.Where(yiji=>yiji.pid==0); foreach (MyShop.Model.Categroy items in first) { ddl.Items.Add(new ListItem(items.caname,items.id.ToString())); var second = list.Where(erji=>erji.pid==items.id); foreach (var item1 in second) { ddl.Items.Add(new ListItem("|--"+item1.caname,item1.id.ToString())); } }
②:上传图片:
第一步:添加FileUpload控件和Button控件。
第二步:上传图片代码:
/// <summary>上传文件方法 /// 返回文件名 /// </summary> /// <param name="myFileUpload">上传控件ID</param> /// <param name="allowExtensions">允许上传的扩展名类型,如:string[] allowExtensions = { ".doc", ".xls", ".ppt", ".jpg", ".gif" };</param> /// <param name="maxLength">允许上传的最大大小,以M为单位</param> /// <param name="savePath">保存文件的目录,注意是绝对路径,如:Server.MapPath("~/upload/");</param> public static string Upload(FileUpload myFileUpload, string[] allowExtensions, int maxLength, string savePath) { // 文件格式是否允许上传 bool fileAllow = false; //检查是否有文件 if (myFileUpload.HasFile) { // 检查文件大小, ContentLength获取的是字节,转换成M的时候要除以2次1024 if (myFileUpload.PostedFile.ContentLength / 1024 / 1024 >= maxLength) { throw new Exception("只能上传小于" + maxLength + "的文件"); } //取得上传文件的后缀名,并转换成小写字母 string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower(); string tmp = ""; // 存储允许上传的文件的后缀名 //检查扩展名是否符合指定类型 for (int i = 0; i < allowExtensions.Length; i++) { tmp += i == allowExtensions.Length - 1 ? allowExtensions[i] : allowExtensions[i] + ","; if (fileExtension == allowExtensions[i]) { fileAllow = true; } } if (fileAllow) { try { string datedir = DateTime.Now.ToString("yyyyMMdd"); if (!Directory.Exists(savePath + datedir)) { Directory.CreateDirectory(savePath + datedir); } string saveName = Guid.NewGuid() + fileExtension; string path = savePath + datedir + "/" + saveName; //存ä?储ä¡é文?件t到Ì?文?件t夹D myFileUpload.SaveAs(path); return datedir + "/" + saveName; } catch (Exception ex) { throw new Exception(ex.Message); } } else { throw new Exception("文件格式不符?,可以上传的文件格式为:" + tmp); } } else { throw new Exception("请选择要上传的文件"); } }第三步:在Button事件中调用第二步的代码,上传图片,并实现图片预览:
//上传 protected void btnUpload_Click(object sender, EventArgs e) { try { string proimg = Upload(fuimg,new string[]{".jpg",".gif",".png"},3,Server.MapPath("~/upload/"));//获取上传的图片 imgYL.ImageUrl = "~/upload/" + proimg;//图片预览 imgYL.ToolTip = proimg;//图片提示 } catch (Exception ex) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "MsgBox", ex.Message); } }
理想化添加商品操作:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; namespace Web.admin { public partial class product_add : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindDDL(); } } //绑定分类列表 private void BindDDL() { ////原来的绑定方式 //List<MyShop.Model.Categroy> list = new MyShop.DAL.CategroyDAO().GetListArray(""); //ddl.DataTextField = "caname"; //ddl.DataValueField = "id"; //ddl.DataSource = list; //ddl.DataBind(); //使用Linq使下列表显示二级分类 List<MyShop.Model.Categroy> list = new MyShop.DAL.CategroyDAO().GetListArray(""); var first = list.Where(yiji=>yiji.pid==0); foreach (MyShop.Model.Categroy items in first) { ddl.Items.Add(new ListItem(items.caname,items.id.ToString())); var second = list.Where(erji=>erji.pid==items.id); foreach (var item1 in second) { ddl.Items.Add(new ListItem("|--"+item1.caname,item1.id.ToString())); } } } /// <summary>上传文件方法 /// 返回文件名 /// </summary> /// <param name="myFileUpload">上传控件ID</param> /// <param name="allowExtensions">允许上传的扩展名类型,如:string[] allowExtensions = { ".doc", ".xls", ".ppt", ".jpg", ".gif" };</param> /// <param name="maxLength">允许上传的最大大小,以M为单位</param> /// <param name="savePath">保存文件的目录,注意是绝对路径,如:Server.MapPath("~/upload/");</param> public static string Upload(FileUpload myFileUpload, string[] allowExtensions, int maxLength, string savePath) { // 文件格式是否允许上传 bool fileAllow = false; //检查是否有文件 if (myFileUpload.HasFile) { // 检查文件大小, ContentLength获取的是字节,转换成M的时候要除以2次1024 if (myFileUpload.PostedFile.ContentLength / 1024 / 1024 >= maxLength) { throw new Exception("只能上传小于" + maxLength + "的文件"); } //取得上传文件的后缀名,并转换成小写字母 string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower(); string tmp = ""; // 存储允许上传的文件的后缀名 //检查扩展名是否符合指定类型 for (int i = 0; i < allowExtensions.Length; i++) { tmp += i == allowExtensions.Length - 1 ? allowExtensions[i] : allowExtensions[i] + ","; if (fileExtension == allowExtensions[i]) { fileAllow = true; } } if (fileAllow) { try { string datedir = DateTime.Now.ToString("yyyyMMdd"); if (!Directory.Exists(savePath + datedir)) { Directory.CreateDirectory(savePath + datedir); } string saveName = Guid.NewGuid() + fileExtension; string path = savePath + datedir + "/" + saveName; //存ä?储ä¡é文?件t到Ì?文?件t夹D myFileUpload.SaveAs(path); return datedir + "/" + saveName; } catch (Exception ex) { throw new Exception(ex.Message); } } else { throw new Exception("文件格式不符?,可以上传的文件格式为:" + tmp); } } else { throw new Exception("请选择要上传的文件"); } } //添加商品 protected void btnadd_Click(object sender, EventArgs e) { string proname = txtname.Text.Trim(); string proimg = imgYL.ToolTip;//img预览的小提示 string marketprice = txtmarket.Text.Trim(); string memberprice = txtmember.Text.Trim(); string vipprice = txtvip.Text.Trim(); string state = txtstate.Text.Trim(); string norm = txtnorm.Text.Trim(); string dw = txtdw.Text.Trim(); //注意DropDownList的用法 string caid = ddl.SelectedValue; //注意CheckBoxList的用法 int istj = cbl.Items[0].Selected ? 1 : 0; int isxp = cbl.Items[1].Selected ? 1 : 0; int isvip = cbl.Items[2].Selected ? 1 : 0; string prodesc = txtdesc.Text.Trim(); new MyShop.DAL.ProductDAO().Add(new MyShop.Model.Product() { proname=proname, proimg=proimg, marketprice=decimal.Parse(marketprice), memberprice = decimal.Parse(memberprice), vipprice=decimal.Parse(vipprice), state=state, norm=norm, dw=dw, caid=int.Parse(caid), istj=istj, isxp=isxp, isvip=isvip, prodesc=prodesc, createDate=DateTime.Now }); Page.ClientScript.RegisterStartupScript(Page.GetType(), "MsgBox", "<script>alert('商品已经添加成功!')</script>"); txtdesc.Text = ""; txtdw.Text = ""; txtmarket.Text = ""; txtmember.Text = ""; txtname.Text = ""; txtnorm.Text = ""; txtstate.Text = ""; txtvip.Text = ""; cbl.ClearSelection(); ddl.ClearSelection(); } //上传 protected void btnUpload_Click(object sender, EventArgs e) { try { string proimg = Upload(fuimg,new string[]{".jpg",".gif",".png"},3,Server.MapPath("~/upload/"));//获取上传的图片 imgYL.ImageUrl = "~/upload/" + proimg;//图片预览 imgYL.ToolTip = proimg;//图片提示 } catch (Exception ex) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "MsgBox", ex.Message); } } } }