MarcusV(南墙大佬的搬运工)

南墙大佬的CSDN博客地址

导航

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创建数据库

在这里插入图片描述

在这里插入图片描述

这是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

在这里插入图片描述

<!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;
        }
    }
}

最后记得改配置文件
在这里插入图片描述

<system.webServer>
    <handlers>
      <add name="test" path="New/*.html" verb="*" type="WebApplication2.BLL.Handler" />
    </handlers>
  </system.webServer>

效果图:

在这里插入图片描述

删除操作
在这里插入图片描述

在这里插入图片描述

详情页面(自动生成页面)
在这里插入图片描述

posted on 2020-05-08 17:00  MarcusV  阅读(130)  评论(0编辑  收藏  举报