【ASP.NET基礎】簡單企業產品展現網站--產品編輯CRUD

摘要:本文記錄建立一個小的、簡單的產品網站的步驟。javascript

一,搭建一個簡單的產品展現網站,熟悉如下知識點:NVelocity模板引擎、Ajax無刷新頁面請求,文件上傳,Row_Number實現分頁,ckEditor使用,Bootstrap的簡單使用。【點擊查看網站效果

二,網站基本框架:新建項目ProductWeb ,並完成基本框架的搭建(SQLHelper,ckEditor,Common_Nvelocity,Bootstrap等添加到項目中)。並建立ProductWebDB 。【下載基本模板框架

三,在基本模板的基礎上,添加後臺 產品列表頁面(ProductList_Admin.html)

  A,新增數據庫: ProduceWebDB 並新建表ProCategories、Productscss

USE [ProduceWebDB]
GO
/****** Object:  Table [dbo].[ProCategories]    Script Date: 2015/6/2 15:54:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ProCategories](
    [CateID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
    [CateName] [varchar](250) NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Products]    Script Date: 2015/6/2 15:54:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Products](
    [ProID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
    [ProName] [nvarchar](250) NOT NULL,
    [ProImagePath] [nvarchar](max) NOT NULL,
    [ProIntroduce] [text] NOT NULL,
    [ProCateID] [bigint] NOT NULL,
    [AddTime] [datetime] NULL,
    [AddIP] [nchar](18) NULL,
    [IsDelete] [bit] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
ALTER TABLE [dbo].[Products] ADD  CONSTRAINT [DF_Products_CreateTime]  DEFAULT (getdate()) FOR [AddTime]
GO
ALTER TABLE [dbo].[Products] ADD  CONSTRAINT [DF_Products_IsDelete]  DEFAULT ((0)) FOR [IsDelete]
GO
View Code

  B,項目新增ProductList_Admin.ashx通常處理程序 , 在Templates/Admin下添加對應的 ProductList_Admin.html 頁面 ,在後臺顯示產品列表。html

Templates/Admin/Head.html: 至關於模板頁的頁頭部分,用Bootstrap導航組件 其餘頁面經過#parse("Head.html")調用
html5

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html;" charset="gb2312" />
    <!-- 這個屬性主要是設置瀏覽器優先使用什麼模式來渲染頁面的-->
    <!-- #下面的meta標籤告訴IE瀏覽器,IE8/9及之後的版本都會以最高版本IE來渲染頁面。  -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />


    <!--移動設備都是這Viewport裏面打開,width=device-width表示打開頁面默認和設備一致,initial-scale=1表示頁面不進行縮放   -->
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <!-- 上述3個meta標籤*必須*放在最前面,任何其餘內容都*必須*跟隨其後! -->
    <title>後臺管理</title>

    <!-- Bootstrap -->
    <!--<link href="css/bootstrap.min.css" rel="stylesheet"/>-->
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css" />

    <!--低版本瀏覽器若是支持HTML5須要添加如下js-->
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="http://cdn.bootcss .com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!--鼠標懸停彈出下拉菜單-->
    <style type="text/css">
        .navbar .nav > li .dropdown-menu {
            margin: 0;
        }

        .navbar .nav > li:hover .dropdown-menu {
            display: block;
        }

        .navbar .nav > li .dropdown-menu > li:hover {
            font-size: larger;
        }
    </style>


</head>
<body>

    <!-- --導航條  默認高度50px, 固定在頂部 -->
    <nav class="navbar navbar-default .navbar-fixed-top">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <!--當瀏覽器寬度變窄的時候會顯示這個Button按鈕,而且會把data-target中的div中ul收縮導航到Button下方-->
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <!--定義小按鈕的樣式-->
                    <span class="sr-only">Toggle navigation</span>
                    <!-- 頁面變窄時 , 按鈕的3條橫線 -->
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <!--Logo位置-->
                <a class="navbar-brand" href="http://www.cnblogs.com/chengzish/">後臺管理</a>

            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <!--導航條內容-->
                    <li class="active"><a href="#">首頁 <span class="sr-only">(current)</span></a></li>

                    <li><a href="#">成功案例編輯</a></li>
                    <li><a href="#">新聞活動編輯</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">服務編輯<span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="#">軟件定製編輯</a></li>
                            <li class="divider"></li>
                            <li><a href="#">外包服務編輯</a></li>
                            <li class="divider"></li>
                            <li><a href="#">諮詢服務編輯</a></li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">OA系統解決方案編輯<span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu">

                            <li><a href="#">員工考勤系統編輯</a></li>
                            <li class="divider"></li>
                            <li><a href="#">薪資結算系統編輯</a></li>
                            <li class="divider"></li>
                            <li><a href="#">門禁管理系統編輯</a></li>
                            <li class="divider"></li>
                            <li><a href="#">APP開發編輯</a></li>

                        </ul>
                    </li>
                </ul>
                <!--搜索表單-->
                <form class="navbar-form navbar-left" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Search" />
                    </div>
                    <button type="submit" class="btn btn-default">搜索</button>
                </form>
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">Git Fork</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">聯繫咱們編輯<span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="#">地址</a></li>
                            <li><a href="#">電話</a></li>
                            <li><a href="#">郵箱</a></li>
                            <li class="divider"></li>
                            <li><a href="#">微信</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container-fluid -->
    </nav>
View Code

Templates/Admin/Foot.html: 至關於模板頁的頁頭部分,標註版權信息,其餘頁面經過#parse("Foot.html")java

<div id="footer" class="container">

    <nav class="navbar navbar-default navbar-fixed-bottom">

        <div class="navbar-inner navbar-content-center">

            <p class="text-muted credit" style="padding: 10px; text-align: center">
                Copyright @2014-2015 By 橙子科技 All Rights Reserved.

            </p>

        </div>

    </nav>
</div>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>

<!-- Bootstrap核心js依賴於jQuery,因此要先引用jQuery-->
<!-- Include all compiled plugins (below), or include individual files as needed -->
<!-- <script src="js/bootstrap.min.js"></script>-->

<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="http://cdn.bootcss.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</body>
</html>
View Code

Templates/Admin/ProductList_Admin.html:  產品列表展現頁面,遍歷顯示產品數據
jquery

#parse("Admin/Head.html")
    <h2>產品列表維護</h2>

<div style="width: 70%; text-align: center; margin-left: 15%;">
    <table class="table table-striped table-bordered table-hover">
        <tr>
            <td>產品名稱</td>
            <td>產品類別</td>
            <td>編輯</td>
            <td>刪除</td>
        </tr>
        #foreach($Pro in $data.Products)
            <tr>
                <td>$Pro.ProName</td>
                <td>$Pro.CateName />
                </td>
                <td><a href="ProductEdit.html?action=edit&id=$Pro.ProID">編輯</a></td>
                <td><a href="ProductEdit.html?action=delete&id=$Pro.ProID">刪除</a></td>
            </tr>
        #end
    </table>
</div>

#parse("Admin/Foot.html")
View Code

ProductList_Admin.ashx: 從數據庫中讀取產品信息
web

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace ProductWeb
{
    /// <summary>
    /// ProductList_Admin 後臺顯示產品列表
    /// </summary>
    public class ProductList_Admin : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            //從DB中選出產品信息
            string sql = "SELECT [ProID],[ProName],[ProImagePath],[ProIntroduce],b.[CateName] as CateName  FROM [dbo].[Products]  as a left join [dbo].[ProCategories] as b on a.ProCateID=b.CateID ";
            SQLHelper sqlH = new SQLHelper();
            DataTable dt = sqlH.ExecuteQuery(sql, CommandType.Text);


            var data = new { PageTitle = "產品列表", Products = dt.Rows };

            string strHtml = Common_Nvelocity.RenderHTML("Admin/ProductList_Admin.html", data);
            context.Response.Write(strHtml);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code

C,Ctrl+F5運行程序,查看 ProductList_Admin.ashx 讀出了DB中的數據:sql

四,添加產品編輯頁面(ProductEdit.html)點擊ProductList_Admin.html中的「編輯」跳轉到ProductEdit.html編輯頁面. 

  PorductEdit.ashx根據傳遞過來的Action(edit,delete,addnew)進行編輯、刪除、新增操做。數據庫

  A, 更新webconfig容許寫入 html 標籤bootstrap

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime requestValidationMode="2.0"/>
  </system.web>
View Code

  B, 添加ProductEdit.html 頁面 (1,三個隱藏控件分別記錄當前頁面是不是首次加載,點擊「保存」按鈕須要執行的操做,傳遞過來的id的值 2, 注意下拉列表的實現)

#parse("Admin/Head.html")
    
<script src="../../ckeditor/ckeditor.js"></script>

<div style="width: 70%; text-align: left; margin-left: 15%;">
    #if($data.ActionEdit=="edit")
         <h2 class="text-center">產品編輯</h2>
    #elseif ($data.ActionEdit=="delete")
         <h2 class="text-center">產品刪除 </h2>
    #elseif ($data.ActionEdit=="addnew")
         <h2 class="text-center">產品新增</h2>
    #end
    <form method="post" action="ProductEdit.ashx">
        <!--三個隱藏,IspostBack 記錄頁面是否首次加載,action 記錄提交按鈕後是須要新增仍是編輯,txtProIDHiddden 隱藏當前編輯的id  -->
        <input type="hidden" name="IsPostBack" value="true" />
        <input type="hidden" name="txtaction" value="$data.ActionEdit" />
        <input type="hidden" name="txtProIDHiddden" value="$data.Product.ProID" />

        <table class="table table-striped table-bordered">

            <tr>
                <td>產品名稱:</td>
                <td>
                    <input type="text" name="txtProName" value="$data.Product.ProName" /></td>
            </tr>

            <tr>
                <td>產品分類:</td>
                <td>
                    <select name="txtProCateID">
                        #foreach($cate in $data.Categories)
                        #if($cate.CateID==$data.Product.ProCateID)
                            <option value="$cate.CateID" selected="selected">$cate.CateName</option>
                        #else
                           <option value="$cate.CateID">$cate.CateName</option>
                        #end
                    #end
                    </select>
                </td>
            </tr>

            <tr>
                <td>產品圖片:</td>
                <td>
                    <img id="ProImg" src="$data.Product.ProImagePath" class="img-rounded" /></td>
            </tr>
            <tr>
                <td>產品介紹:</td>
                <td>
                    <textarea id="idProIntroduce" name="txtProIntroduce">$data.Product.ProIntroduce </textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align: center">
                    <input type="submit" value="保存" class="btn btn-primary" />
                    <a href="ProductList_Admin.ashx" class="btn btn-default">返回</a>
                </td>
            </tr>
        </table>


    </form>
    <div style="width: 70%; text-align: center; margin-left: 15%;">
        <script type="text/javascript">
            var txtIntro = document.getElementById("idProIntroduce");
            CKEDITOR.replace(txtIntro);

        </script>
#parse("Admin/Foot.html")
View Code

  C, 添加ProductEdit.ashx 處理新增、編輯、刪除操做,並把數據交給Nvelocity模板從而加載到前臺頁面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace ProductWeb
{
    /// <summary>
    /// ProductEdit Product編輯頁面 
    /// </summary>
    public class ProductEdit : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string strHtml = "";
            string sqlCates = "SELECT [CateID],[CateName] FROM [dbo].[ProCategories]";
            SQLHelper sqlH = new SQLHelper();
            DataTable dtCates = sqlH.ExecuteQuery(sqlCates, CommandType.Text);

            //[ProID],[ProName],[ProImagePath],[ProIntroduce],[ProCateID],b.[CateName] as CateName,b.[CateID] as CateID  FROM [Products]  as a left join [ProCategories] as b on a.ProCateID=b.CateID and a.ProID=@strProID ";     //
            ////定義Product,並給一個默認的控制 
            var ProductOriginal = new { ProID = 0, ProName = "", ProImagePath = "", ProIntroduce = "", CateName = "", CateID = "" };


            //頁面首次加載 , 顯示Product信息
            if (string.IsNullOrEmpty(context.Request.Form["IsPostBack"]) == true)
            {
                string strProID = context.Request.QueryString["id"];   // 點擊 編輯 按鈕,傳遞過來 action 和 id值
                string strAction = context.Request.QueryString["action"] == null ? "" : context.Request.QueryString["action"].ToString().ToLower(); //  點擊保存後,具體是 edit、 delte仍是 add,  保存在頁面的隱藏控件中
                string strPageTitle = "產品操做";  //default

                if (!string.IsNullOrEmpty(strProID))   // id 存在
                {
                    //從DB中選出 id 對應的Product 信息
                    SqlParameter[] sqlParas = new SqlParameter[] { 
                        new SqlParameter("@strProID",strProID)
                    };

                    if (strAction == "edit")
                    {
                        strPageTitle = "產品編輯";
                    }
                    else if (strAction == "delete")
                    {
                        strPageTitle = "產品刪除";
                    }
                    else if (strAction == "addnew")
                    {
                        strPageTitle = "產品新增";
                    }
                    //選擇出ID對應的Product
                    DataTable dtPro = dtGetProductByID(strProID);
                    int numExist = 0;
                    numExist = dtPro.Rows.Count;

                    if (numExist > 0)
                    {
                        // 產品存在,顯示產品信息
                        var data = new { PageTitle = strPageTitle, Categories = dtCates.Rows, Product = dtPro.Rows[0], ActionEdit = strAction };
                        strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                    }
                    else
                    {
                        // 不存在,顯示編輯頁面
                        var data = new { PageTitle = strPageTitle, Categories = dtCates.Rows, Product = ProductOriginal, ActionEdit = strAction };
                        strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                    }
                }
                else
                {
                    //顯示編輯頁面
                    var data = new { PageTitle = strPageTitle, Categories = dtCates.Rows, Product = ProductOriginal, ActionEdit = strAction };
                    strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                }

            }
            //點擊了 submit 按鈕,根據傳遞過來的action進行操做 update/delete
            else
            {
                string strAction = context.Request.Form["txtaction"];
                if (!string.IsNullOrEmpty(strAction))
                {
                    string strInfo = "";
                    if (strAction == "edit")
                    {

                        string strProID = context.Request.Form["txtProIDHiddden"];
                        string strProName = context.Request.Form["txtProName"];
                        string strProCateID = context.Request.Form["txtProCateID"];
                        //string strProImagePath = context.Request.Form["strProImgPath"];
                        string strProIntroduce = context.Request.Form["txtProIntroduce"];


                        //選擇出ID對應的Product
                        DataTable dtPro = dtGetProductByID(strProID);
                        int numExist = 0;
                        numExist = dtPro.Rows.Count;
                        if (numExist > 0)
                        {
                            //update
                            string sqlUpdate = "update [Products] set [ProName]=@ProName,[ProIntroduce]=@ProIntroduce,[ProCateID]=@ProCateID where [IsDelete]=0 and [ProID]=@ProID ";
                            SqlParameter[] sqlParas = new SqlParameter[] { 
                                new SqlParameter("@ProName",strProName),
                                new SqlParameter("@ProCateID",strProCateID),
                                new SqlParameter("@ProIntroduce",strProIntroduce),
                                new SqlParameter("@ProID",strProID)
                            };
                            int numSuccUpd = 0;
                            numSuccUpd = sqlH.ExecuteNonQuery(sqlUpdate, sqlParas, CommandType.Text);

                            if (numSuccUpd > 0)
                            {
                                strInfo = "更新成功";
                                DataTable dtProNew = dtGetProductByID(strProID);
                                var data = new { PageTitle = "產品編輯", Categories = dtCates.Rows, Product = dtProNew.Rows[0], ActionEdit = strAction, InfoMeg = strInfo };
                                strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                            }
                            else
                            {
                                strInfo = "更新失敗";
                                DataTable dtProNew = dtGetProductByID(strProID);
                                var data = new { PageTitle = "產品編輯", Categories = dtCates.Rows, Product = dtProNew.Rows[0], ActionEdit = strAction, InfoMeg = strInfo };
                                strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                            }
                        }
                    }
                    else if (strAction == "delete")
                    {
                        string strProID = context.Request.Form["txtProIDHiddden"];
                        //選擇出ID對應的Product
                        DataTable dtPro = dtGetProductByID(strProID);
                        int numExist = 0;
                        numExist = dtPro.Rows.Count;
                        if (numExist > 0)
                        {
                            string sqlUpdate = "update [Products] set [IsDelete]=1  where  [ProID]=@ProID ";
                            SqlParameter[] sqlParas = new SqlParameter[] { 
                                new SqlParameter("@ProID",strProID)
                            };
                            int numSuccUpd = 0;
                            numSuccUpd = sqlH.ExecuteNonQuery(sqlUpdate, sqlParas, CommandType.Text);
                            if (numSuccUpd > 0)
                            {
                                strInfo = "刪除成功";
                                context.Response.Redirect("productlist_admin.ashx");
                            }
                            else
                            {
                                DataTable dtProNew = dtGetProductByID(strProID);
                                var data = new { PageTitle = "產品刪除", Categories = dtCates.Rows, Product = dtProNew.Rows[0], ActionEdit = strAction, InfoMeg = strInfo };
                                strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                            }
                        }

                    }
                    else if (strAction == "addnew")
                    {
                        //寫入數據庫

                        string strProName = context.Request.Form["txtProName"];
                        string strProCateID = context.Request.Form["txtProCateID"];
                        string strProImagePath = "updloadFiles/3.jpg";
                        string strProIntroduce = context.Request.Form["txtProIntroduce"];
                        if (string.IsNullOrEmpty(strProName) || string.IsNullOrEmpty(strProCateID) || string.IsNullOrEmpty(strProIntroduce))
                        {
                            strInfo = "不容許爲空";
                            var data = new { PageTitle = "產品新增", Categories = dtCates.Rows, Product = ProductOriginal, MesgInfo = strInfo };
                            strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                        }
                        else
                        {
                            string sqlInsert = "  insert into [Products]([ProName],[ProCateID],[ProIntroduce],[ProImagePath]) values(@ProName,@ProCateID,@ProIntroduce,@ProImagePath) ";
                            SqlParameter[] sqlParas = new SqlParameter[] { 
                                new SqlParameter("@ProName",strProName),
                                new SqlParameter("@ProCateID",strProCateID),
                                new SqlParameter("@ProIntroduce",strProIntroduce),
                                 new SqlParameter("@ProImagePath",strProImagePath)
                            };
                            int numSucc = sqlH.ExecuteNonQuery(sqlInsert, sqlParas, CommandType.Text);
                            if (numSucc == 1)
                            {
                                strInfo = "添加成功";
                                context.Response.Redirect("productlist_admin.ashx");
                            }
                            else
                            {
                                strInfo = "添加失敗";
                                var data = new { PageTitle = "產品新增", Categories = dtCates.Rows, Product = ProductOriginal, MesgInfo = strInfo };
                                strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                            }
                        }

                    }
                }
                else
                {
                    var data = new { PageTitle = "產品編輯", Categories = dtCates.Rows, Product = ProductOriginal, MesgInfo = "" };
                    strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                }

            }
            context.Response.Write(strHtml);
        }

        public DataTable dtGetProductByID(string strProID)
        {
            SQLHelper sqlH = new SQLHelper();
            //選擇出ID對應的Product
            string sqlPro = "SELECT [ProID],[ProName],[ProImagePath],[ProIntroduce],[ProCateID],b.[CateName] as CateName,b.[CateID] as CateID  FROM [Products]  as a left join [ProCategories] as b on a.ProCateID=b.CateID where [IsDelete]=0 and a.ProID=@ProID ";
            SqlParameter[] sqlParas = new SqlParameter[] { 
                                     new SqlParameter("@ProID", strProID)
                                };

            DataTable dtPro = sqlH.ExecuteQuery(sqlPro, sqlParas, CommandType.Text);
            return dtPro;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code

---------------------------------------------------實現效果: 新增 AddNew---------------------------------------------------

----------------------------------------------------實現效果:  編輯 Edit-------------------------------------------------------

----------------------------------------------------實現效果:  刪除 Delete-----------------------------------------------------

五,實現圖片上傳和分頁 (知識點:1,From表單設置enctype屬性 2,文件上傳並SaveAs到Server.MapPath  3,Row_Number()進行分頁

  A,分別更新ProductEdit.html和ProductEdit.ashx 實現圖片的上傳和更新(圖片存儲在服務器,圖片名稱存儲DB)

Templates/Admin/ProductEdit.html:  Form表單添加enctype="multipart/form-data"屬性 ,圖片src讀取圖片路徑

#parse("Admin/Head.html")
    
<script src="../../ckeditor/ckeditor.js"></script>

<div style="width: 70%; text-align: left; margin-left: 15%;">
    #if($data.ActionEdit=="edit")
         <h2 class="text-center">產品編輯</h2>
    #elseif ($data.ActionEdit=="delete")
         <h2 class="text-center">產品刪除 </h2>
    #elseif ($data.ActionEdit=="addnew")
         <h2 class="text-center">產品新增</h2>
    #end
    <form method="post" action="ProductEdit.ashx" enctype="multipart/form-data">
        <!--三個隱藏,IspostBack 記錄頁面是否首次加載,action 記錄提交按鈕後是須要新增仍是編輯,txtProIDHiddden 隱藏當前編輯的id  -->
        <input type="hidden" name="IsPostBack" value="true" />
        <input type="hidden" name="txtaction" value="$data.ActionEdit" />
        <input type="hidden" name="txtProIDHiddden" value="$data.Product.ProID" />

        <table class="table table-striped table-bordered">

            <tr>
                <td>產品名稱:</td>
                <td>
                    <input type="text" name="txtProName" value="$data.Product.ProName" /></td>
            </tr>

            <tr>
                <td>產品分類:</td>
                <td>
                    <select name="txtProCateID">
                        #foreach($cate in $data.Categories)
                        #if($cate.CateID==$data.Product.ProCateID)
                            <option value="$cate.CateID" selected="selected">$cate.CateName</option>
                        #else
                           <option value="$cate.CateID">$cate.CateName</option>
                        #end
                    #end
                    </select>
                </td>
            </tr>

            <tr>
                <td>產品圖片:</td>
                <td>#if ($data.ActionEdit=="addnew")
                    <input type="file" name="ProductImage" value="上傳圖片" />
                    #else
                    <img id="ProImg" src="../../uploadFiels/$data.Product.ProImagePath" class="img-rounded" style="width: 40px; height: 40px" />
                    <input type="file" name="ProductImage" value="更新圖片" />
                    #end

                </td>
            </tr>
            <tr>
                <td>產品介紹:</td>
                <td>
                    <textarea id="idProIntroduce" name="txtProIntroduce">$data.Product.ProIntroduce </textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align: center">
                    <input type="submit" value="保存" class="btn btn-primary" />
                    <a href="ProductList_Admin.ashx" class="btn btn-default">返回</a>
                </td>
            </tr>
        </table>
    </form>

    <br />
    <br />
    <br />
    <script type="text/javascript">
        var txtIntro = document.getElementById("idProIntroduce");
        CKEDITOR.replace(txtIntro);
    </script>
#parse("Admin/Foot.html")
View Code

ProductEdit.ashx:   實現圖片保存到uploadfiles文件夾,圖片名稱保存到DB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace ProductWeb
{
    /// <summary>
    /// ProductEdit Product編輯頁面 
    /// </summary>
    public class ProductEdit : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string strHtml = "";
            string sqlCates = "SELECT [CateID],[CateName] FROM [dbo].[ProCategories]";
            SQLHelper sqlH = new SQLHelper();
            DataTable dtCates = sqlH.ExecuteQuery(sqlCates, CommandType.Text);

            //[ProID],[ProName],[ProImagePath],[ProIntroduce],[ProCateID],b.[CateName] as CateName,b.[CateID] as CateID  FROM [Products]  as a left join [ProCategories] as b on a.ProCateID=b.CateID and a.ProID=@strProID ";     //
            ////定義Product,並給一個默認的控制 
            var ProductOriginal = new { ProID = 0, ProName = "", ProImagePath = "", ProIntroduce = "", CateName = "", CateID = "" };


            //頁面首次加載 , 顯示Product信息
            if (string.IsNullOrEmpty(context.Request.Form["IsPostBack"]) == true)
            {
                string strProID = context.Request.QueryString["id"];   // 點擊 編輯 按鈕,傳遞過來 action 和 id值
                string strAction = context.Request.QueryString["action"] == null ? "" : context.Request.QueryString["action"].ToString().ToLower(); //  點擊保存後,具體是 edit、 delte仍是 add,  保存在頁面的隱藏控件中
                string strPageTitle = "產品操做";  //default

                if (!string.IsNullOrEmpty(strProID))   // id 存在
                {
                    //從DB中選出 id 對應的Product 信息
                    SqlParameter[] sqlParas = new SqlParameter[] { 
                        new SqlParameter("@strProID",strProID)
                    };

                    if (strAction == "edit")
                    {
                        strPageTitle = "產品編輯";
                    }
                    else if (strAction == "delete")
                    {
                        strPageTitle = "產品刪除";
                    }
                    else if (strAction == "addnew")
                    {
                        strPageTitle = "產品新增";
                    }
                    //選擇出ID對應的Product
                    DataTable dtPro = dtGetProductByID(strProID);
                    int numExist = 0;
                    numExist = dtPro.Rows.Count;

                    if (numExist > 0)
                    {
                        // 產品存在,顯示產品信息
                        var data = new { PageTitle = strPageTitle, Categories = dtCates.Rows, Product = dtPro.Rows[0], ActionEdit = strAction };
                        strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                    }
                    else
                    {
                        // 不存在,顯示編輯頁面
                        var data = new { PageTitle = strPageTitle, Categories = dtCates.Rows, Product = ProductOriginal, ActionEdit = strAction };
                        strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                    }
                }
                else
                {
                    //顯示編輯頁面
                    var data = new { PageTitle = strPageTitle, Categories = dtCates.Rows, Product = ProductOriginal, ActionEdit = strAction };
                    strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                }

            }
            //點擊了 submit 按鈕,根據傳遞過來的action進行操做 update/delete
            else
            {
                string strAction = context.Request.Form["txtaction"];
                if (!string.IsNullOrEmpty(strAction))
                {
                    string strInfo = "";
                    if (strAction == "edit")
                    {

                        string strProID = context.Request.Form["txtProIDHiddden"];
                        string strProName = context.Request.Form["txtProName"];
                        string strProCateID = context.Request.Form["txtProCateID"];
                        string strProImageName = ""; //文件名
                        string strProIntroduce = context.Request.Form["txtProIntroduce"];


                        //選擇出ID對應的Product
                        DataTable dtPro = dtGetProductByID(strProID);
                        int numExist = 0;
                        numExist = dtPro.Rows.Count;
                        if (numExist > 0)
                        {

                            //上傳文件
                            HttpPostedFile proImg = context.Request.Files["ProductImage"];  //得到客戶端上傳圖片信息
                            string imgServerPath = context.Server.MapPath("~/uploadFiels/"); //項目中 uploadFiles路徑
                            string strTimeNow = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                            strProImageName = strTimeNow + Path.GetExtension(proImg.FileName);
                            if ((Path.GetExtension(proImg.FileName) == ".jpg" || Path.GetExtension(proImg.FileName) == ".png") && proImg.ContentLength < 102400)
                            {
                                proImg.SaveAs(imgServerPath + strProImageName);       //上傳
                            }
                            //update DB
                            string sqlUpdate = "update [Products] set [ProName]=@ProName,[ProIntroduce]=@ProIntroduce,[ProCateID]=@ProCateID,[ProImagePath]=@ProImagePath where [IsDelete]=0 and [ProID]=@ProID ";
                            SqlParameter[] sqlParas = new SqlParameter[] { 
                                new SqlParameter("@ProName",strProName),
                                new SqlParameter("@ProCateID",strProCateID),
                                new SqlParameter("@ProIntroduce",strProIntroduce),
                                new SqlParameter("@ProID",strProID),
                                new SqlParameter("@ProImagePath",strProImageName)
                            };
                            int numSuccUpd = 0;
                            numSuccUpd = sqlH.ExecuteNonQuery(sqlUpdate, sqlParas, CommandType.Text);

                            if (numSuccUpd > 0)
                            {
                                strInfo = "更新成功";
                                DataTable dtProNew = dtGetProductByID(strProID);
                                var data = new { PageTitle = "產品編輯", Categories = dtCates.Rows, Product = dtProNew.Rows[0], ActionEdit = strAction, InfoMeg = strInfo };
                                strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                            }
                            else
                            {
                                strInfo = "更新失敗";
                                DataTable dtProNew = dtGetProductByID(strProID);
                                var data = new { PageTitle = "產品編輯", Categories = dtCates.Rows, Product = dtProNew.Rows[0], ActionEdit = strAction, InfoMeg = strInfo };
                                strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                            }
                        }
                    }
                    else if (strAction == "delete")
                    {
                        string strProID = context.Request.Form["txtProIDHiddden"];
                        //選擇出ID對應的Product
                        DataTable dtPro = dtGetProductByID(strProID);
                        int numExist = 0;
                        numExist = dtPro.Rows.Count;
                        if (numExist > 0)
                        {
                            string sqlUpdate = "update [Products] set [IsDelete]=1  where  [ProID]=@ProID ";
                            SqlParameter[] sqlParas = new SqlParameter[] { 
                                new SqlParameter("@ProID",strProID)
                            };
                            int numSuccUpd = 0;
                            numSuccUpd = sqlH.ExecuteNonQuery(sqlUpdate, sqlParas, CommandType.Text);
                            if (numSuccUpd > 0)
                            {
                                strInfo = "刪除成功";
                                context.Response.Redirect("productlist_admin.ashx");
                            }
                            else
                            {
                                DataTable dtProNew = dtGetProductByID(strProID);
                                var data = new { PageTitle = "產品刪除", Categories = dtCates.Rows, Product = dtProNew.Rows[0], ActionEdit = strAction, InfoMeg = strInfo };
                                strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                            }
                        }

                    }
                    else if (strAction == "addnew")
                    {
                        //寫入數據庫

                        string strProName = context.Request.Form["txtProName"];
                        string strProCateID = context.Request.Form["txtProCateID"];
                        string strProImageName = "";
                        string strProIntroduce = context.Request.Form["txtProIntroduce"];


                        if (string.IsNullOrEmpty(strProName) || string.IsNullOrEmpty(strProCateID) || string.IsNullOrEmpty(strProIntroduce))
                        {
                            strInfo = "不容許爲空";
                            var data = new { PageTitle = "產品新增", Categories = dtCates.Rows, Product = ProductOriginal, MesgInfo = strInfo };
                            strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                        }
                        else
                        {
                            //上傳文件
                            HttpPostedFile proImg = context.Request.Files["ProductImage"];  //得到客戶端上傳圖片信息
                            string imgServerPath = context.Server.MapPath("~/uploadFiels/"); //項目中 uploadFiles路徑
                            string strTimeNow = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                            strProImageName = strTimeNow + Path.GetExtension(proImg.FileName);
                            if ((Path.GetExtension(proImg.FileName) == ".jpg" || Path.GetExtension(proImg.FileName) == ".png") && proImg.ContentLength < 102400)
                            {
                                proImg.SaveAs(imgServerPath + strProImageName);       //上傳
                            }
                            // Insert DB
                            string sqlInsert = "  insert into [Products]([ProName],[ProCateID],[ProIntroduce],[ProImagePath]) values(@ProName,@ProCateID,@ProIntroduce,@ProImagePath) ";
                            SqlParameter[] sqlParas = new SqlParameter[] { 
                                new SqlParameter("@ProName",strProName),
                                new SqlParameter("@ProCateID",strProCateID),
                                new SqlParameter("@ProIntroduce",strProIntroduce),
                                new SqlParameter("@ProImagePath",strProImageName)
                            };
                            int numSucc = sqlH.ExecuteNonQuery(sqlInsert, sqlParas, CommandType.Text);
                            if (numSucc == 1)
                            {
                                strInfo = "添加成功";
                                context.Response.Redirect("productlist_admin.ashx");
                            }
                            else
                            {
                                strInfo = "添加失敗";
                                var data = new { PageTitle = "產品新增", Categories = dtCates.Rows, Product = ProductOriginal, MesgInfo = strInfo };
                                strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                            }
                        }

                    }
                }
                else
                {
                    var data = new { PageTitle = "產品編輯", Categories = dtCates.Rows, Product = ProductOriginal, MesgInfo = "" };
                    strHtml = Common_Nvelocity.RenderHTML("Admin/ProductEdit.html", data);
                }

            }
            context.Response.Write(strHtml);
        }
        // Query Product By ID
        public DataTable dtGetProductByID(string strProID)
        {
            SQLHelper sqlH = new SQLHelper();
            //選擇出ID對應的Product
            string sqlPro = "SELECT [ProID],[ProName],[ProImagePath],[ProIntroduce],[ProCateID],b.[CateName] as CateName,b.[CateID] as CateID  FROM [Products]  as a left join [ProCategories] as b on a.ProCateID=b.CateID where [IsDelete]=0 and a.ProID=@ProID ";
            SqlParameter[] sqlParas = new SqlParameter[] { 
                                     new SqlParameter("@ProID", strProID)
                                };

            DataTable dtPro = sqlH.ExecuteQuery(sqlPro, sqlParas, CommandType.Text);
            return dtPro;
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code

--------------------------圖片上傳-效果--------------------------------------------

  B,藉助SQL的Row_Number方法進行分頁, 前臺頁面傳入頁碼到後臺,而後查詢對應頁碼的數據。(1,Row_Number 2,頁碼計算 3,根據當前頁面把上一頁、下一頁禁用)

    分別更新ProductList_Admin.html  和 ProductList_Admin.ashx頁面:

Templates/Admin/ProductList_Admin.html    調用Bootstrap分頁組件

#parse("Admin/Head.html")


<h2 class="text-center">產品列表維護</h2>

<div style="width: 70%; text-align: center; margin-left: 15%;">
    <table class="table table-striped table-bordered table-hover">
        <tr style="font-weight: bolder">

            <td>產品名稱</td>
            <td>產品類別</td>
            <td>編輯</td>
            <td>刪除</td>
        </tr>
        #foreach($Pro in $data.Products)
            <tr>
                <td>$Pro.ProName</td>
                <td>$Pro.CateName</td>

                <td><a href="ProductEdit.ashx?action=edit&id=$Pro.ProID">編輯</a></td>
                <td><a href="ProductEdit.ashx?action=delete&id=$Pro.ProID">刪除</a></td>

            </tr>
        #end
        <tr>
            <td colspan="4" class="text-center">
                <nav>
                    <ul class="pagination">
                        #if($data.PageBeforeNext.PageBefore==0)
                        <li class="disabled">
                        #else 
                        <li>#end
                            <a href="Productlist_admin.ashx?Page=$data.PageBeforeNext.PageBefore" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>

                        #foreach($pageHref in $data.PageData)
                          <li><a href="$pageHref.Href">$pageHref.Title</a></li>
                        #end


                        #if($data.PageBeforeNext.PageNext>=$data.PageNums)
                        <li class="disabled">
                        #else 
                        <li>#end
                            <a href="Productlist_admin.ashx?Page=$data.PageBeforeNext.PageNext" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                        <li><a>共$data.PageNums頁</a></li>
                    </ul>
                </nav>
            </td>
        </tr>
        <tr>
            <td colspan="4" class="text-center">
                <a href="ProductEdit.ashx?action=AddNew" class="btn btn-default">新增</a></td>
        </tr>
    </table>
</div>

#parse("Admin/Foot.html")
View Code

ProductList_Admin.ashx: 1,頁數計算,理解Row_Number分頁  2,生成對應的href連接傳遞給前臺頁面 3, 當前頁碼、頁面總數、上頁、下頁

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;


namespace ProductWeb
{
    /// <summary>
    /// ProductList_Admin 後臺顯示產品列表
    /// </summary>
    public class ProductList_Admin : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";


            //從DB中選出產品信息
            SQLHelper sqlH = new SQLHelper();
            //DataTable是把數據讀取出來之後放入內存中,若是數據量大的話 一次性都讀出來的話就很吃內存形成系統性能不好
            //這時候咱們就要從DB中只讀取咱們須要的數據就行了 , 把數據進行分頁處理,只讀取須要頁數的數據

            // 一,頁數計算。查詢出來Product總數numAllProducts. 總頁數numPages=Celling(numAllProducts/10.0) .  天花板函數的結果是  >=這個數的最小整數
            int numAllProducts = Convert.ToInt32(sqlH.ExecuteScalar("select count(*) from [Products] where [IsDelete]=0", CommandType.Text));
            int numPages = (int)Math.Ceiling(numAllProducts / 10.0);  // 5/10→1  10/10→1   11/10→2

            //二,生成前臺頁面 a 的連接地址 href
            object[] objPageData = new object[numPages];
            for (int i = 0; i < numPages; i++)
            {
                objPageData[i] = new { Href = "ProductList_Admin.ashx?Page=" + (i + 1).ToString(), Title = (i + 1).ToString() };
            }

            //三,根據前臺傳遞過來的頁碼,查詢對應頁面的數據
            int intRowNumber = 1; //默認爲第1頁 1-10條數據,第2頁: 11~20條數據  (intRowNumber-1)*10+1~intRowNumber*10
            string strPageNumber = context.Request.QueryString["Page"];
            if (!string.IsNullOrEmpty(strPageNumber))
            {
                intRowNumber = Convert.ToInt32(strPageNumber);  //獲取傳遞過來的頁面
            }

            //選擇對應頁面的數據
            string sql = @"select * from 
                           (SELECT [ProID],[ProName],[ProImagePath],[ProIntroduce],[ProCateID],b.[CateName] as CateName,b.[CateID] as CateID,ROW_NUMBER() over (order by ProID) as RowNum  
                             FROM [Products]  as a left join [ProCategories] as b on a.ProCateID=b.CateID where [IsDelete]=0 ) as s
                             where s.RowNum between (@IntRowNumber-1)*10+1 and @IntRowNumber*10    ";

            SqlParameter[] sqlParas = new SqlParameter[] { 
                new SqlParameter("@IntRowNumber",intRowNumber)
            };
            //string sql = "SELECT [ProID],[ProName],[ProImagePath],[ProIntroduce],b.[CateName] as CateName  FROM [dbo].[Products]  as a left join [dbo].[ProCategories] as b on a.ProCateID=b.CateID where [IsDelete]=0 ";
            DataTable dt = sqlH.ExecuteQuery(sql, sqlParas, CommandType.Text);

            //四,根據當天頁碼和總頁面數,設置前一頁和後一頁
            var varPageBeforeNext = new { PageBefore = intRowNumber - 1, PageNext = intRowNumber + 1 };

            var data = new { PageTitle = "產品列表", Products = dt.Rows, PageData = objPageData, PageNums = numPages, PageBeforeNext = varPageBeforeNext };

            string strHtml = Common_Nvelocity.RenderHTML("Admin/ProductList_Admin.html", data);
            context.Response.Write(strHtml);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code

--------------------------------------------------分頁實現效果------------------------------------------------------

 

 

 

 

總結:本文實現了產品編輯的增刪查改功能,瞭解圖片上傳、分頁實現等。  【Demo下載 】   

 

參考:

NVelocity 語法: http://www.cnblogs.com/hxling/archive/2011/10/23/2221918.html

Row_Number()使用: http://www.cnblogs.com/gy51Testing/archive/2012/07/26/2609832.html

相關文章
相關標籤/搜索