【C#】MVC+EF+LINQ 綜合小項目


第一,創建數據庫

 

 

 

 

 create table category(
id int primary key,
name nvarchar(20)
)

create table news(
id int primary key,
title nvarchar(20),
content nvarchar(200),
createTime datetime ,
caid int constraint fk_ca_id foreign key references category(id)
)



create table comment(
id int primary key,
content nvarchar(100),
createTime dateTime,
userIp nvarchar(50),
newsId int constraint fk_news_id foreign key references news(id)
)

 

 

手動添加數據

 

 

第二,創建MVC工程文件

 

 

第三,在Models文件夾下創建 EF

 

 

第四,修改3個頁面

1.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBlog.Models;
using System.Data;

namespace MVCBlog.Controllers
{
    public class HomeController : Controller
    {

        /// <summary>
        /// 數據上下文對象
        /// </summary>
        BlogDBEntities db = new BlogDBEntities();

            #region 查詢新聞列表+ActionResult Index()
            /// <summary>
            /// 查詢新聞列表
            /// </summary>
            /// <returns></returns>
            public ActionResult Index()
            {
                //1.查詢數據庫里的新聞數據(通過EF執行)
                //1.1第一種方法:使用SQO(標准查詢運算符),查詢所有新聞
                //db.news.Where(d =>d.id  !=0 );
                //List<Models.news> list = db.news.Where(d => d.id != 0).ToList ();

                //1.2第二種方法:使用linq語句,查詢所有新聞標題
                //Linq僅僅是給程序員使用的語法糖,.net編譯器會在編譯時將linq轉化為sqo
                List<Models.news> list = (from d in db.news where d.id != 0 select d).ToList();

                //2.將數據集合傳給視圖
                ViewData["datalist"] = list;

                //3.加載視圖

                return View();
            }
            #endregion

            #region 執行刪除操作(根據id)+ActionResult Del(int id)
            /// <summary>
            /// 執行刪除操作(根據id)
            /// </summary>
            /// <param name="id">要刪除的新聞id</param>
            /// <returns></returns>
            public ActionResult Del(int id)
            {
                try
                {
                    //1.創建要刪除的對象
                    news modelDel = new news() { id = id };
                    //2.將對象添加到EF管理容器中
                    db.news.Attach(modelDel);
                    //3.將對象包裝類的狀態標識為刪除狀態
                    db.news.Remove(modelDel);
                    //4.更新到數據庫
                    db.SaveChanges();
                    //5.更新成功,則令瀏覽器跳轉到list方法
                    return RedirectToAction("Index", "Home");
                }
                catch (Exception ex)
                {
                    return Content("刪除失敗!" + ex.Message);
                }
            }
            #endregion

            #region 顯示要修改的數據(根據id)+ActionResult Modify(int id)
            [HttpGet]
            /// <summary>
            /// 執行修改操作(根據id)
            /// </summary>
            /// <param name="id">要修改的新聞id</param>
            /// <returns></returns>
            public ActionResult Modify(int id)
            {
                try
                {
                    //根據id查詢數據庫,返回集合中,拿到第一個實體對象
                    news n = (from a in db.news where a.id == id select a).FirstOrDefault();
                    //生成分類下拉框列表集合List<SelectListItem> list
                    IEnumerable<SelectListItem> listitem = (from c in db.categories select c).ToList().Select(c => new SelectListItem { Value = c.id.ToString(), Text = c.name });
                    ViewBag.CateList = listitem;

                    //將n傳遞給視圖顯示 viewbag 或者viewdata

                    //加載視圖,使用view的構造函數 將數據傳給視圖上的名為model的屬性
                    return View(n);
                }
                catch (Exception ex)
                {
                    return Content("修改失敗!" + ex.Message);
                }
            }
            #endregion

            #region 執行修改操作+ActionResult Modify(news model)
            [HttpPost]
            /// <summary>
            /// 執行修改操作
            /// </summary>
            /// <param name="model"></param>
            /// <returns></returns>
            public ActionResult Modify(news model)
            {
                try
                {
                    //將實體對象加入到EF對象容器中,並獲取偽包裝類對象
                    var entry = db.Entry<news>(model);
                    //將包裝類對象的狀態設置為unchanged
                    entry.State = System.Data.Entity.EntityState.Unchanged;
                    //設置需要提交的實體屬性
                    entry.Property(a => a.title).IsModified = true;
                    entry.Property(a => a.content).IsModified = true;
                    //提交到數據庫 完成修改
                    db.SaveChanges();
                    //5.更新成功,則令瀏覽器跳轉到list方法
                    return RedirectToAction("Index", "Home");
                }
                catch (Exception ex)
                {
                    return Content("修改失敗!" + ex.Message);
                }

            }
            #endregion

        }

  }

2.

<span style="font-size:18px;">
    @using MVCBlog.Models
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
    <style type="text/css">
        #tblist {
            border: 1px solid #0ff;
            width: 800px;
            margin: 10px auto;
            border-collapse: collapse;
        }

            #tblist th, td {
                border: 1px solid #0ff;
                padding: 10px;
            }
    </style>
    <script type="text/javascript">
        function Del(id) {
            alert("運行到了這里");
            if (confirm("您確定要刪除嗎?親~~")) {
                window.location = "/Home/Del/" + id;
            }
        }
        function Modify(id) {
            window.location = "/Home/Modify/" + id;
        }

    </script>
</head>
<body>
    <table id="tblist">
        <tr>
            <th>id</th>
            <th>標題</th>
            <th>發布時間</th>
            <th>新聞分類</th>
            <th>操作</th>
        </tr>

        <!--遍歷Action方法 設置給viewdata的數據集合,生成html代碼-->
        @foreach (news n in ViewData["datalist"] as List<news>)
        {
            <tr>
                <td>@n.id </td>
                <td>@n.title </td>
                <td>@n.createTime </td>
                <td>@n.caid </td>
                <td>
                    <a href="javascript:Del(@n.id) ">刪除</a>
                    <a href="javascript:Modify(@n.id )">修改</a>
                </td>
            </tr>
        }
    </table>
</body>
</html>
</span>

3.

<span style="font-size:18px;">
    @model MVCBlog.Models.news
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>修改</title>
    <style type="text/css">
        #tblist {
            border: 1px solid #0ff;
            width: 600px;
            margin: 10px auto;
            border-collapse: collapse;
        }

            #tblist th, td {
                border: 1px solid #0ff;
                padding: 10px;
            }
    </style>
</head>
<body>
    @using (Html.BeginForm("Modify", "Home", FormMethod.Post))
    {
        <table id="tblist">
            <tr>
                <td colspan="2">修改 @Html.HiddenFor(a => a.id)</td>
            </tr>
            <tr>
                <td>標題:</td>
                @*<td >@Html.TextBox("txtName",(object )Model.title)</td>*@
                <!--使用htmlhelper的強類型方法直接從model中根據title屬性生成文本框-->
                <td>@Html.TextBoxFor(a => a.title)</td>
            </tr>
            <tr>
                <td>分類:</td>
                <td>@Html.DropDownListFor(a => a.category, ViewBag.CateList as IEnumerable<SelectListItem>)</td>
            </tr>
            <tr>
                <td>內容:</td>
                <td>@Html.TextAreaFor(a => a.content, 10, 60, null)</td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="確定修改" />@Html.ActionLink("返回", "Index", "Home")</td>
            </tr>
        </table>
    }
</body>
</html>
</span>

 

 

第四,頁面運行實現

 

 

 

 

 

第五,BUG   將List修改為去取兩個表關聯的數據,前后台的修改。

 

 

 

 

 

代碼下載地址:             鏈接:https://pan.baidu.com/s/1_4NKrIqM51EPOMJLSWSB0Q
                                 提取碼:wpjc


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM