天天看點

ASP.NET關于書籍詳情和删除的Demo(HttpHandler進行頁面靜态化[自動生成html網頁]+Entity Framework通過類建立資料庫+EF删查)

這次的Demo如标題所示,

首先第一步EF建立資料庫

建立兩個類,一個是圖書類,一個是圖書類别的類

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace WebApplication2.DAL
{
    public class Book
    {
        [Key]
        public int BookId { get; set; }
        public string BookName { get; set; }
        public string BookAuthor { get; set; }
        public virtual BookType TypeId { get; set; }
        public decimal Price { get; set; }
        public DateTime Addtime { get; set; }
        public string Img { get; set; }
    }
}
           
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace WebApplication2.DAL
{
    public class BookType
    {
        [Key]
        public int TypeId { get; set; }
        public string TyoeName { get; set; } 
    }
}
           

添加一個ef建立資料庫

ASP.NET關于書籍詳情和删除的Demo(HttpHandler進行頁面靜态化[自動生成html網頁]+Entity Framework通過類建立資料庫+EF删查)
ASP.NET關于書籍詳情和删除的Demo(HttpHandler進行頁面靜态化[自動生成html網頁]+Entity Framework通過類建立資料庫+EF删查)

這是EF自動生成的那個類,下面畫橫線的是需要自己寫的,第一行是一個添加資料的類,稍後會在下面附上

ASP.NET關于書籍詳情和删除的Demo(HttpHandler進行頁面靜态化[自動生成html網頁]+Entity Framework通過類建立資料庫+EF删查)
namespace WebApplication2.DAL
{
    using System;
    using System.Data.Entity;
    using System.Linq;

    public class Model1 : DbContext
    {
        //您的上下文已配置為從您的應用程式的配置檔案(App.config 或 Web.config)
        //使用“Model1”連接配接字元串。預設情況下,此連接配接字元串針對您的 LocalDb 執行個體上的
        //“WebApplication2.DAL.Model1”資料庫。
        // 
        //如果您想要針對其他資料庫和/或資料庫提供程式,請在應用程式配置檔案中修改“Model1”
        //連接配接字元串。
        public Model1()
            : base("name=Model1")
        {
            Database.SetInitializer(new InitDataBase());
        }
        public virtual DbSet<Book> Books { get; set; }

        public virtual DbSet<BookType> BookTypes { get; set; }

        //為您要在模型中包含的每種實體類型都添加 DbSet。有關配置和使用 Code First  模型
        //的詳細資訊,請參閱 http://go.microsoft.com/fwlink/?LinkId=390109。

        // public virtual DbSet<MyEntity> MyEntities { get; set; }
    }

    //public class MyEntity
    //{
    //    public int Id { get; set; }
    //    public string Name { get; set; }
    //}
}
           

自動加載資料的類

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

namespace WebApplication2.DAL
{
    public class InitDataBase : DropCreateDatabaseIfModelChanges<Model1>
    { 
        protected override void Seed(Model1 context)
        {
            BookType bookType1 = new BookType
            {
                TyoeName = "武俠"
            };
            BookType bookType4 = new BookType
            {
                TyoeName = "科幻"
            };
            BookType bookType2 = new BookType
            {
                TyoeName = "文學"
            };
            BookType bookType3 = new BookType
            {
                TyoeName = "技術"
            };
            
            Book bookInfo = new Book
            {
                BookName = "笑傲江湖",
                BookAuthor = "金庸",
                TypeId = bookType1,
                Price = 38,
                Addtime = DateTime.Now,
                Img = "1.jpg"
            };
            Book bookInfo1 = new Book
            {
                BookName = "ASP.NAT進階",
                BookAuthor = "張三",
                TypeId = bookType3,
                Price = 88,
                Addtime = DateTime.Now,
                Img = "2.jpg"
            };
            Book bookInfo2 = new Book
            {
                BookName = "圍城",
                BookAuthor = "錢鐘書",
                TypeId = bookType2,
                Price = 46,
                Addtime = DateTime.Now,
                Img = "3.jpg"
            };
            Book bookInfo3 = new Book
            {
                BookName = "末日霸權",
                BookAuthor = "夢裡銀河",
                TypeId = bookType1,
                Price = 26,
                Addtime = DateTime.Now,
                Img = "4.jpg"
            };
            Book bookInfo4 = new Book
            {
                BookName = "蕭十一郎",
                BookAuthor = "古龍",
                TypeId = bookType1,
                Price = 39,
                Addtime = DateTime.Now,
                Img = "5.jpg"
            };
            Book bookInfo5 = new Book
            {
                BookName = "C#從入門到精通",
                BookAuthor = "李四",
                TypeId = bookType3,
                Price = 66,
                Addtime = DateTime.Now,
                Img = "6.jpg"
            };
            Book bookInfo6 = new Book
            {
                BookName = "C#從入門到精通",
                BookAuthor = "李四",
                TypeId = bookType3,
                Price = 66,
                Addtime = DateTime.Now,
                Img = "6.jpg"
            };
            context.Books.Add(bookInfo);
            context.Books.Add(bookInfo1);
            context.Books.Add(bookInfo2);
            context.Books.Add(bookInfo3);
            context.Books.Add(bookInfo4);
            context.Books.Add(bookInfo5);
            context.Books.Add(bookInfo6);
            context.BookTypes.Add(bookType4);
            context.BookTypes.Add(bookType1);
            context.BookTypes.Add(bookType2);
            context.BookTypes.Add(bookType3);
        }
    }
}
           

一個index.aspx頁面前台和背景代碼

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebApplication2.Index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <th scope="col">圖書編号</th>
                    <th scope="col">圖書名稱</th>
                    <th scope="col">圖書價格</th>
                    <th scope="col">作者</th>
                    <th scope="col">類型</th>
                    <th scope="col">圖檔</th>
                    <th scope="col">上架時間</th>
                    <th scope="col">操作</th>
                </tr>
                <asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
                    <ItemTemplate>
                        <tr>  <th scope="row"><%# Eval("BookId") %></th>
                                    <td><%# Eval("BookName") %></td>
                                    <td><%# Eval("Price") %></td>
                                    <td><%# Eval("BookAuthor") %></td>
                                    <td><%# Eval("TypeId.TyoeName") %></td>
                                    <td>
                                        <asp:Image ID="Image1" runat="server" ImageUrl='<%# "~/images/"+ Eval("Img") %>' Width="60" Height="60" /></td>
                                    <td><%# Eval("Addtime") %></td>
                                    <td>
                                        <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("BookId") %>' CommandName="delete" OnClientClick="return confirm('确定删除嗎?')">删除</asp:LinkButton>
                                        <asp:LinkButton ID="LinkButton2" runat="server" CommandArgument='<%# Eval("BookId") %>' CommandName="xainq">詳情</asp:LinkButton>
                                        
                                    </td>
                                </tr>
                        </tr>
                    </ItemTemplate>

                </asp:Repeater>
            </table>
        </div>
    </form>
</body>
</html>

           

背景

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication2.DAL;

namespace WebApplication2
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                select();
            }
        }
        private void select()
        {
            using (Model1 db = new Model1())
            {
                var list = db.Books.ToList();
                Repeater1.DataSource = list;
                Repeater1.DataBind();
            }
        }

        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            //LinkButton的CommandName,就是操作的标記
            string pand = e.CommandName;
            int id = Convert.ToInt32(e.CommandArgument);
            if (pand == "delete")
            {
                using (Model1 db = new Model1())
                {
                    var sc = db.Books.FirstOrDefault(s => s.BookId == id);
                    db.Books.Remove(sc);
                    db.SaveChanges();
                    select();
                }
            }
            if (pand == "xainq")
            {
                Response.Redirect("New/Info_" + (id - 1) + ".html");
            }
        }
    }
}
           

這裡還需要做一個模型的html

ASP.NET關于書籍詳情和删除的Demo(HttpHandler進行頁面靜态化[自動生成html網頁]+Entity Framework通過類建立資料庫+EF删查)
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <img src="../images/{$Img}" />
    <p>圖書名稱:{$BookName}</p>
    <p>圖書價格:{$Price}</p>
</body>
</html>
           

再來一個handler的類,這個類是自動生成網頁的

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using WebApplication2.DAL;

namespace WebApplication2.BLL
{
    public class Handler : IHttpHandler
    {
        public bool IsReusable => true;

        public void ProcessRequest(HttpContext context)
        {
            string url = context.Request.RawUrl;
            int last = url.LastIndexOf("_");
            int dot = url.LastIndexOf(".");
            int newId = int.Parse(url.Substring(last + 1, dot - last - 1)) ;
            string userFilePath = context.Server.MapPath("~/NEW/info_" + newId + ".html");
            if (!File.Exists(userFilePath))
            {
                using (Model1 bd = new Model1())
                {
                    List<Book> news = bd.Books.ToList();
                    string tempPath = context.Server.MapPath("~/New/Temp.html");
                    //一個建立得
                    string tempHtml = ReadTemplate(tempPath);
                    //替換裡面得變量
                    tempHtml = tempHtml.Replace("{$Img}", news[newId].Img);
                    tempHtml = tempHtml.Replace("{$Price}", news[newId].Price.ToString());
                    tempHtml = tempHtml.Replace("{$BookName}", news[newId].BookName);
                    //一個輸出翻譯得檔案
                    WriteHtmlFile(userFilePath, tempHtml);
                }

            }
            context.Response.WriteFile(userFilePath);
        }

        private void WriteHtmlFile(string userFilePath, string tempHtml)
        {
            FileStream fs = new FileStream(userFilePath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(tempHtml);
            sw.Close();
            fs.Close();
        }

        private string ReadTemplate(string tempPath)
        {
            if (!File.Exists(tempPath))
            {
                throw new Exception("新聞詳情頁面模闆檔案未找到!");
            }
            FileStream fs = new FileStream(tempPath, FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            string tempHtml = sr.ReadToEnd();
            sr.Close();
            fs.Close();
            return tempHtml;
        }
    }
}
           

最後記得改配置檔案

ASP.NET關于書籍詳情和删除的Demo(HttpHandler進行頁面靜态化[自動生成html網頁]+Entity Framework通過類建立資料庫+EF删查)
<system.webServer>
    <handlers>
      <add name="test" path="New/*.html" verb="*" type="WebApplication2.BLL.Handler" />
    </handlers>
  </system.webServer>
           

效果圖:

ASP.NET關于書籍詳情和删除的Demo(HttpHandler進行頁面靜态化[自動生成html網頁]+Entity Framework通過類建立資料庫+EF删查)

删除操作

ASP.NET關于書籍詳情和删除的Demo(HttpHandler進行頁面靜态化[自動生成html網頁]+Entity Framework通過類建立資料庫+EF删查)
ASP.NET關于書籍詳情和删除的Demo(HttpHandler進行頁面靜态化[自動生成html網頁]+Entity Framework通過類建立資料庫+EF删查)

詳情頁面(自動生成頁面)

ASP.NET關于書籍詳情和删除的Demo(HttpHandler進行頁面靜态化[自動生成html網頁]+Entity Framework通過類建立資料庫+EF删查)

繼續閱讀