20140625三层架构实现产品的增删改查

产品的增删改查

l  Model: Products.cs

    public class Products

    {

        public System.Guid Id { get; set; }

        public System.String Name { get; set; }

        public System.String ImagePath { get; set; }

        public System.String Msg { get; set; }

        public System.Guid CategoryId { get; set; }

    }

l  三层架构:

         DAL层:

        public Products ToModel(DataRow row)

        {

            Products model = new Products();

           

            model.Name = (System.String)SqlHelper.FromDBNull(row["Name"]);

            model.Id = (System.Guid)SqlHelper.FromDBNull(row["Id"]);

            model.ImagePath = (System.String)SqlHelper.FromDBNull(row["ImagePath"]);

            model.Msg = (System.String)SqlHelper.FromDBNull(row["Msg"]);

            model.CategoryId = (System.Guid)SqlHelper.FromDBNull(row["CategoryId"]);

            return model;

        }

 

        //ProductCaName类别名称专用ToModel

        public ProductCaName ToModelCaName(DataRow row)

        {

            ProductCaName model = new ProductCaName();

            model.Id = (System.Guid)SqlHelper.FromDBNull(row["Id"]);

            model.Name = (System.String)SqlHelper.FromDBNull(row["Name"]);

            model.CategoryId = (System.Guid)SqlHelper.FromDBNull(row["CategoryId"]);

            model.CategoryName = (System.String)SqlHelper.FromDBNull(row["CategoryName"]);

            return model;

        }

        //ProductCaName类别名称专用ListAll

        public ProductCaName[] ListAllCaName()

        {

            DataTable table = SqlHelper.ExecuteReader(@"select p.Id as Id,p.Name as Name,p.CategoryId as CategoryId

            ,c.Name as CategoryName  from T_Products p left join

            T_ProductCategories c on p.CategoryId=c.Id");

            ProductCaName[] items = new ProductCaName[table.Rows.Count];

            for (int i = 0; i < table.Rows.Count; i++)

            {

                ProductCaName item = ToModelCaName(table.Rows[i]);

                items[i] = item;

            }

            return items;

        }

        public Products[] ListAll()

        {

            DataTable table = SqlHelper.ExecuteReader("select * from T_Products");

            Products[] items = new Products[table.Rows.Count];

            for (int i = 0; i < table.Rows.Count; i++)

            {

                Products item = ToModel(table.Rows[i]);

                items[i] = item;

            }

            return items;

        }

        public Products GetById(Guid id)

        {

            DataTable table = SqlHelper.ExecuteReader("select * from T_Products where [email protected]", new SqlParameter("@Id", id));

            if (table.Rows.Count <= 0)

            {

                return null;

            }

            else if (table.Rows.Count == 1)

            {

                return ToModel(table.Rows[0]);

            }

            else

            {

                throw new Exception();

            }

          

        }

        public void Insert(Products model)

        {

            SqlHelper.ExecuteNonQuery(@"INSERT INTO T_Products

                (Id,Name,ImagePath,Msg,CategoryId)

                 values (@Id,@Name,@ImagePath,@Msg,@CategoryId)"

             , new SqlParameter("@Id", SqlHelper.ToDBValue(model.Id))

             , new SqlParameter("@Name", SqlHelper.ToDBValue(model.Name))

             , new SqlParameter("@ImagePath", SqlHelper.ToDBValue(model.ImagePath))

             , new SqlParameter("@Msg", SqlHelper.ToDBValue(model.Msg))

             , new SqlParameter("@CategoryId", SqlHelper.ToDBValue(model.CategoryId))

            );

        }

        public void DeleteById(Guid id)

        {

            SqlHelper.ExecuteNonQuery("delete from T_Products where [email protected]"

             , new SqlParameter("@Id", id));

        }

        public void Update(Products model)

        {

            SqlHelper.ExecuteNonQuery(@"Update T_Products set [email protected],

                    [email protected],

                    [email protected],

                    [email protected] where [email protected]"

             , new SqlParameter("@Name", SqlHelper.ToDBValue(model.Name))

             , new SqlParameter("@ImagePath", SqlHelper.ToDBValue(model.ImagePath))

             , new SqlParameter("@Msg", SqlHelper.ToDBValue(model.Msg))

             , new SqlParameter("@CategoryId", SqlHelper.ToDBValue(model.CategoryId))

             , new SqlParameter("@Id", model.Id));

        }

        //获得指定Id的图片路径(ImagePath)

        public string GetImagePathById(Guid id)

        {

            Products products = GetById(id);

            return products.ImagePath;

 

        }

    }

BLL层:

public class ProductsBLL

    {

        public Products[] ListAll()

        {

            ProductsDAL productsdal = new ProductsDAL();

            return  productsdal.ListAll();

        }

        //显示类别名字专用

        public ProductCaName[] ListAllCaName()

        {

            ProductsDAL productsdal = new ProductsDAL();

            return productsdal.ListAllCaName();

        }

        //根据指定Id返回Model

        public Products GetById(Guid id)

        {

            ProductsDAL productsdal = new ProductsDAL();

            return productsdal.GetById(id);

        }

        public Products ToModel(DataRow model)

        {

            ProductsDAL productsdal = new ProductsDAL();

            return productsdal.ToModel(model);

        }

        public void Insert(Products model)

        {

            ProductsDAL productsdal = new ProductsDAL();

            productsdal.Insert(model);

        }

 

        //产品更新

        public void Update(Products model)

        {

            ProductsDAL productsdal = new ProductsDAL();

            productsdal.Update(model);

        }

        //获得指定Id的图片文件路径

        public string GetImagePathById(Guid id)

        {

            ProductsDAL productsdal = new ProductsDAL();

            return productsdal.GetImagePathById(id);

        }

 

        public void DeleteById(Guid id)

        {

            ProductsDAL productsdal = new ProductsDAL();

            productsdal.DeleteById(id);

        }

 

    }

UI层:

模板:

ProductList.htm

#parse("Admin/Head.htm")

<form action="../Admin/ProductList.ashx" method="post">

<input type="hidden" name="IsPostBack"/>

    <p><a href="ProductEdit.ashx?Action=AddNew">新增产品</a></p>

    <table>   

        <thead>

            <tr><td>编辑&nbsp;&nbsp;&nbsp;&nbsp;</td><td>删除&nbsp;&nbsp;&nbsp;&nbsp;</td><td>名称&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td>类别名称&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>

        </thead>

        <tbody>       

            #foreach($p in $Model.Products)

                <tr><td><a href="ProductEdit.ashx?Action=Edit&Id=$p.Id">编辑</a></td>

                <td><a href="ProductEdit.ashx?Action=Delete&Id=$p.Id" >删除</a></td>

              

                <td><a href="">$p.Name</a></td>

                <td>$p.CategoryName</td></tr>

            #end

        </tbody>

 

    </table>

</form>

#parse("Admin/Foot.htm")

ProductEdit.htm

#parse("Admin/Head.htm")

<script type="text/javascript" src="../js/ckeditor/ckeditor.js"></script>

<form method="post" action="../Admin/ProductEdit.ashx" enctype="multipart/form-data">

    <input type="hidden" name="IsPostBack" value="true"/>

    <input type="hidden" name="Action" value="$Model.Action"/>

    <input type="hidden" name="Id" value="$Model.Product.Id"/>

    <p>名称:<input type="text" name="Name" value="$Model.Product.Name"/></p>

    <p>分类:<select name="CategoryId">

                #foreach($c in $Model.Categories)

                  #if($c.Id==$Model.Product.CategoryId)

                  <option value="$c.Id" selected>$c.Name</option>

                  #else

                  <option value="$c.Id">$c.Name</option>

                  #end

                #end       

            </select>     

    </p>

   <p>产品图片:<input type="file" name="ProductImage"/>

     #if($Model.Action=="Edit")

    <img src="../$Model.Product.ImagePath" width="150" height="100" />

    #end

    </p>

    <p>产品描述:<textarea id="Msg" name="Msg">$Model.Product.Msg</textarea></p>

    <script type="text/javascript">

        var msg = document.getElementById("Msg");

        CKEDITOR.replace(msg);

    </script>

    <p><input type="submit" value="保存" /></p>

</form>

#parse("Admin/Foot.htm")

一般处理程序的处理逻辑:

l  ProductList.ashx

public void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/html";

            // var data = new { Title = "管理员产品管理" };

            ProductsBLL productsbll = new ProductsBLL();

            ProductCaName[] products = productsbll.ListAllCaName();

            var data = new { Title = "管理员产品管理", Products = products };

            string html = CommonHelper.RenderHtml("Admin/ProductList.htm", data);

            context.Response.Write(html); 

        }

l  ProductEdit.ashx

public void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/html";

            ProductCategoriesBLL productCa=new ProductCategoriesBLL();

            ProductCategories[] categories = productCa.ListAll();

            bool isPostBack = !string.IsNullOrEmpty(context.Request["IsPostBack"]);

            string action = context.Request["Action"];

            if (isPostBack)

            {

                //新增保存

                if (action == "AddNew")

                {

                    //数据的合法性检查(服务器端和客户端都要做)数据格式合法性、是否为空、

                    //todo

                    string name = context.Request["Name"];

                    System.Guid categoryId = new Guid(context.Request["CategoryId"]);//将字符串转换为Guid的形式

                    /*------------------------图片的上传处理-------------------------------------------*/

                    //要设定enctype="multipart/form-data"

                    HttpPostedFile productImg = context.Request.Files["ProductImage"];//获得浏览器上传的文件信息

                    //productImg.SaveAs("d:/");//图片要保存到项目的文件夹(子文件夹)下,才可以通过web来访问图片

                    //为了不把路径写死,方便移植采用下面方法

                    string filename =

                        DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + Path.GetExtension(productImg.FileName);//有bug的,一毫秒内多个人上传多个文件

                    //保证无bug的方法是用Guid作为文件名

                    productImg.SaveAs(context.Server.MapPath("~/UI/uploadfile/" + filename));//文件保存路径//得到当前时间的年月日小时分秒毫秒格式

                    //productImg.SaveAs("");//图片要保存到项目的文件夹或者子文件夹下(服务器硬盘上),才可以通过web来访问图片

                    //不能将图片保存路径写死,如果项目移植操作不便

                    //mappath可以把一个相对于网站根目录的文件或者文件夹的路径转换为在服务器磁盘上的物理全路径

                    //获得浏览器上传的文件信息(input type="file" 上传上来的信息)

                    //产品描述

                    /*------------------------图片的上传处理完成-------------------------------------------*/

 

 

                    string msg = context.Request["Msg"];

                    ProductsBLL productsbll = new ProductsBLL();

                    System.Guid id = System.Guid.NewGuid();

                   

 

                    /*----------------------定义DataRow并赋值-------------------------*/

                    DataTable dt = new DataTable();

                    dt.Columns.Add(new DataColumn("Id", typeof(Guid)));

                    dt.Columns.Add(new DataColumn("Name", typeof(string)));

                    dt.Columns.Add(new DataColumn("ImagePath", typeof(string)));

                    dt.Columns.Add(new DataColumn("CategoryId", typeof(Guid)));

                    dt.Columns.Add(new DataColumn("Msg", typeof(string)));

 

                    DataRow dr;

                    dr = dt.NewRow();

                    dr["Name"] = name;

                    dr["ImagePath"] = "uploadfile/" + filename;

                    dr["CategoryId"] = categoryId;

                    dr["Msg"] = msg;

                    dr["Id"] = id;

                    dt.Rows.Add(dr);

                    /*--------------------------------------------------------------------*/

                    Products products = productsbll.ToModel(dr);

                    productsbll.Insert(products);

                    context.Response.Redirect("ProductList.ashx");

 

                }

                else if (action == "Edit")//编辑保存

                {

                    System.Guid id = new Guid(context.Request["Id"]);

                    string name = context.Request["Name"];

                    System.Guid categoryId = new Guid(context.Request["CategoryId"]);

                    /*----------------------图片处理-------------------------*/

                    HttpPostedFile productImg = context.Request.Files["ProductImage"];

                   

                    /*--------------------------------------------------*/

 

 

                    string msg=context.Request["Msg"];

 

                    if (CommonHelper.HasFile(productImg))//用户选择了新的图片

                    {

                        /*----------------------定义DataRow并赋值-------------------------*/

                        DataTable dt = new DataTable();

                        dt.Columns.Add(new DataColumn("Id", typeof(Guid)));

                        dt.Columns.Add(new DataColumn("Name", typeof(string)));

                        dt.Columns.Add(new DataColumn("ImagePath", typeof(string)));

                        dt.Columns.Add(new DataColumn("CategoryId", typeof(Guid)));

                        dt.Columns.Add(new DataColumn("Msg", typeof(string)));

 

                        DataRow dr;

                        dr = dt.NewRow();

                        dr["Name"] = name;

                        string filename = DateTime.Now.ToString("yyyyMMddHHmmssfffffff")

                            + Path.GetExtension(productImg.FileName);//有bug的,一毫秒内多个人上传多个文件

                        productImg.SaveAs(context.Server.MapPath("~/UI/uploadfile/" + filename));

 

                        dr["ImagePath"] = "uploadfile/" + filename;

                        dr["CategoryId"] = categoryId;

                        dr["Msg"] = msg;

                        dr["Id"] = id;

                        dt.Rows.Add(dr);

                        /*--------------------------------------------------------------------*/

                        ProductsBLL productsbll = new ProductsBLL();

                        Products products = productsbll.ToModel(dr);

                        productsbll.Update(products);

                        context.Response.Redirect("ProductList.ashx");

                    }

                    else//用户没有选择新图片,还用之前的产品图片

                    {

                        /*----------------------定义DataRow并赋值-------------------------*/

                        DataTable dt = new DataTable();

                        dt.Columns.Add(new DataColumn("Id", typeof(Guid)));

                        dt.Columns.Add(new DataColumn("Name", typeof(string)));

                        dt.Columns.Add(new DataColumn("ImagePath", typeof(string)));

                        dt.Columns.Add(new DataColumn("CategoryId", typeof(Guid)));

                        dt.Columns.Add(new DataColumn("Msg", typeof(string)));

 

                        DataRow dr;

                        dr = dt.NewRow();

                        dr["Name"] = name;

 

                        ProductsBLL productsbll = new ProductsBLL();

                        dr["ImagePath"] = productsbll.GetImagePathById(id);

 

                        dr["CategoryId"] = categoryId;

                        dr["Msg"] = msg;

                        dr["Id"] = id;

                        dt.Rows.Add(dr);

                        /*--------------------------------------------------------------------*/

                        Products products = productsbll.ToModel(dr);

                        productsbll.Update(products);

                        context.Response.Redirect("ProductList.ashx");

                    }

                }

               

                else

                {

                    context.Response.Write("Action错误!" + action);

                }

 

            }

            else

            {               

                if (action == "AddNew")

                {

                    var data = new

                    {

                        Title = "新增产品",

                        Action = action,

                        Product = new { Id = 0, Name = "", CategoryId = 0, Msg = "" },

                        Categories = categories

                    };

                    string html = CommonHelper.RenderHtml("Admin/ProductEdit.htm", data);

                    context.Response.Write(html);

                }

                else if(action=="Edit")

                {

                    System.Guid id = new Guid(context.Request["Id"]);

                    ProductsBLL productsbll = new ProductsBLL();

                    Products products = productsbll.GetById(id);

                    var data = new {Title="编辑产品",

                    Action=action,

                    Product=products,

                    Categories = categories};

                    string html = CommonHelper.RenderHtml("Admin/ProductEdit.htm", data);

                    context.Response.Write(html);

                }

                else if (action == "Delete")

                {

                    ProductsBLL productsbll = new ProductsBLL();

                    System.Guid id = new Guid(context.Request["Id"]);

                    productsbll.DeleteById(id);

                    context.Response.Write("Id=" + id + "的产品删除成功!");

                    context.Response.Redirect("ProductList.ashx");

                }

                else

                {

                    context.Response.Write("Action错误!" + action);

                }              

            }

        }

20140625三层架构实现产品的增删改查,布布扣,bubuko.com

时间: 2024-10-21 17:07:20

20140625三层架构实现产品的增删改查的相关文章

MVC项目实践,在三层架构下实现SportsStore-11,使用Knockout实现增删改查

SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管理.图像上传......是不错的MVC实践项目,但该项目不是放在多层框架下开发的,离真实项目还有一段距离.本系列将尝试在多层框架下实现SportsStore项目,并用自己的方式实现一些功能. 本篇为"在三层架构下实现SportsStore"系列的第十一篇,包括: ■ 13.使用Knocko

JavaEE使用三层架构(显示层、业务逻辑层、数据访问层)实现数据的增删改查

实例: 1.功能描述 实现一个简易新闻发布系统,包括查看.添加.修改和删除新闻等基本功能 2.具体要求 (1) 创建数据库 newssystem,创建表 news,要求如下: (2) 程序运行时,显示'发布新闻'页面(如图 1),输入相关内容,单击'提交'按钮,将新闻内容添加到数据库 (3) 单击图 1 中的'查看'按钮,显示'查看新闻'页面(如图 2),增加'修改'和'删除'链接 (4) 单击图 2 中的'update'链接,显示'修改新闻'页面(如图 3),修改后单击'修改'按钮确认,单击'

关于C#三层架构增删改查中的“删除”问题

序: 刚学习C#,经过一段时间学习,现在正在做一个简单的前后台联通的项目(主要是C#三层架构实现增删改查).分享一点儿小经验,也供自己以后可以回头看看自己的码农之路. 内容: 主要分享的是一条删除会用到的语句:   int id = Convert.ToInt32  (e.CommandArgument.ToString());   获取到ID,进而进行"删除"功能的实现. 结尾: 就这样一条简单的语句,折腾了我快两个小时了.看来我的"天资"不行啊,不过也反映了自己

MVC实例及用三层架构实现对学生信息的增删改查

一.MVC设计模式实例 M层 Login.java package org.entity; public class Login { private int id; private String uname; private String upwd; public Login() { } public Login( String uname, String upwd) { this.uname = uname; this.upwd = upwd; } public Login(int id, S

EF5(6) 简单三层 增删改查

1:项目结构 2:每层添加对其他层的引用,这里我们把除了Web层之外的所有的层生成的文件都放到解决方案下的Library文件夹下,然后每个项目分别来引用里面的dll项目文件. 我们在Model项目上,右键属性->生成-> 在下面的输出里面,选择上一级的 Library文件夹 2.2 我们调整项目的生成顺序 ,在解决方案或者是任意项目上右键,选择 生成依赖项,调整各个项目的依赖,这样的目的就是调整项目的生成顺序. 注意,这里你选择依赖项,并没有给项目与项目之间增加了dll的引用,只是单纯的修改了

三层架构与四大天王之——增

1.上集回顾   上篇文章我们介绍了三层架构的运行机制,其中包含了对实体类的理解,而后又以简单的登录为例展示了一下,接下来就让我们看看三层架构与"四大天王"的交互. 所谓的四大天王也就是对数据的四大操作--增.删.改.查,这四个功能是最基本,也是最主要的.那么,下面我们就来展示一下如何利用三层向数据库中增加数据.    2.增        (1)UI层         首先是由用户向U层输入要添加的数据                                   以下是确认添

(写给像我一样刚离开校园进入公司的小菜鸟)在领域架构下,如何实现简单的展示页面以及增删改查(第一步)

第一次到公司,现在进行的项目已经开始了有一段时间了,底层架构早已搭建好,经过一段时间熟悉,现在为自己记录一下 大致结构如此图所示,我们需要完成的任务只需要涉及三个类库Domain,Model,Web 流程如下: 1.Model: 1.1 Entities文件=>>新建实体模型 2.Domain: 2.0 Domain类库下有个模型工厂文件件ModelCreateFactory在里面添加实体模型与数据模型转换的TSETZAaaaModelFactory.cs 代码如下 1 using Syste

设置Sql server用户对表、视图、存储过程、架构的增删改查权限

根据数据库Schema限制用户对数据库的操作行为 授予Shema dbo下对象的定义权限给某个用户(也就是说该用户可以修改架构dbo下所有表/视图/存储过程/函数的结构) use [Your DB NAME] GRANT VIEW DEFINITION ON SCHEMA :: dbo to [THE USER NAME] 回收某个用户对Shema dbo下对象的定义权限(也就是说该用户不可以修改架构dbo下所有表/视图/存储过程/函数的结构) use [Your DB NAME] DENY V

restful 架构风格的curd(增删改查)

restful架构 概念:REST指的是一组架构约束条件和原则,如果一个架构符合REST的约束条件和原则,就称之为RESTful架构. restful不是一个专门的技术,他是一个规范.规范就是写写代码给类命名,给属性命名,创建包结构 等等都最好按一定的规则来进行.这样的话以后代码看起来更规范,更容易理解.好比以前写增删改查请求的路径. 优点: 可以方便的实现程序的前后台代码的分离 resutful要求每个请求都是无状态的 可以使请求的路径更规范 使用restful风格实现部门的增删改查 第一步,