.net Core 自我學習隨筆(四)——工作的核心:增刪改查

上次介紹了一下如何進行連接數據庫,我們連了一個 SQL Server 試了試,感覺還是比較良好的。

但是有人說,不會數據庫操作。什麼怎麼怎麼查詢,怎麼怎麼插入(上次不是演示了嗎?),還有怎麼怎麼修改,對了刪除不了怎麼辦。什麼怎麼樣,該怎麼辦就怎麼辦——汪。。。

一、查:
查,是我們常用的操作。比如,向用戶展示相關信息,相關的數據等等。怎麼操作呢?我們來一步一步進行操作。

first:我們先把 Home/IndexController 與 View/index.cshtml 裏面的進行修改,代碼如下:

先改 HomeController:

using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace testProject.Controllers
{
    public class HomeController : Controller
    {
        Model.myDataBase db = new Model.myDataBase();

        public IActionResult Index()
        {
            var userlist = from u in db.Users
                           select u;

            ViewBag.userList = userlist;
            ViewBag.userCount = userlist.Count();

            return View();
        }
    }
}

1、Model.myDataBase db = new Model.myDataBase();
不必說了,我們先準備好數據庫對象,以遍進行數據庫操作,所以,我把其作爲類的一個屬性,而不是方法裏面的變量。這樣可以在需要時直接調用。

2、public IActionResult Index()
這就相當於原來 .net 裏的 public ActionResult Index()。在 .net core 中,全是在 ActionResult 前面加個“I”。其它的都一樣啦。

3、var userlist = from u in db.Users select u;
這個就是執行 Linq 進行查詢操作。

4、ViewBag.xxx 就是向視圖(View)進行數據傳輸,也就是向前端傳輸顯示的內容。

我們已經知道了有“public IActionResult Index()”,就要在視圖(View)中建立一個對應的 index.cshtml,那我們建立一下,具體代碼如下:

Views/Home/index.cshtml

@{
    ViewData["Title"] = "主頁";
}

<style type="text/css">
    .tableStyleBorder {margin: 0px auto; margin-top: 30px; border-collapse: collapse; border: 1px solid Black;}
    .tableStyleBorder th, .tableStyleBorder td {min-width: 80px; text-align: center; padding: 8px; border: 1px solid Black;}
</style>

<table class="tableStyleBorder">
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>創建時間</th>
    </tr>
    @if(0 < ViewBag.userCount)
    {
        @foreach (var item in ViewBag.userList)
        {
    <tr>
        <td>@item.id</td>
        <td>@item.name</td>
        <td>@item.createtime</td>
    </tr>
        }
    }
    else
    {
    <tr>
        <td colspan="3">沒有數據</td>
    </tr>
    }
</table>

1、ViewBag.xxx 就是對應“控制器”(Controller 文件夾中的 CS 文件裏)中的 ViewBag.xxx(見 HomeController.cs)。執行順便是,先執行 控制器,得到的數據通過 ViewBag 傳給 index.cshtml。

2、@if、@foreach:前者判斷,後者遍歷。其實有些 .net 基礎的都能看明白。如果看不明白,請查書——最基礎的知識呀~~~

執行結果:
這裏寫圖片描述

二、增:
增加我們已經知道了,只不過,我們做得再好一些。讓數據從前端傳過來。因爲,我們爲此要做一個“控制器”和一個“視圖”。

HomeController 增加一個方法:

[HttpGet]
public IActionResult writeUser()
{
    return View();
}

這裏我們看到比之前的 index() 多了一個 [HttpGet],這個是指定只有 Get 才能訪問的意思。爲什麼要加這個,我們在後面寫入數據庫時,就能看出來了。

建立對應的視圖
Views/Home/writeUser.cshtml:

<div style="margin-top: 30px;">
    @using (Html.BeginForm("writeUser", "Home", FormMethod.Post))
    {
        <label>姓名:</label>
        @Html.TextBox("username")
        <input type="submit" id="btnSubmit" name="btnSubmit" />
    }
</div>

其中 Html.BeginForm 與 HTML 中的 form 標籤 是一個意思,FormMethod.Post 就是 method=”post”。而 “writeUser”, “Home”,就是 Home/writeUser。如果有 .net MVC 基礎的一看就明白了。其實與原來的沒有區別。@Html.TextBox,就是 input name=”text” 這標籤。

這裏完全也可以用 HTML 來寫,也沒有區別:

<div style="margin-top: 30px;">
    <from action="/Home/writeUser" method="post">
        <label>姓名:</label>
        <input type="text" id="username" name="username" />
        <input type="submit" id="btnSubmit" name="btnSubmit" />
    </form>
</div>

以上的執行效果是:
這裏寫圖片描述

通過上面的代碼,我們知道,在你點擊提交時,代碼會轉到 Home/writeUser,但 writeUser 只支持 Get 方式訪問,但這裏是 post 提交數據,所以我們這時要在“控制器”中來個函數重載,代碼如下:

[HttpPost]
public string writeUser(string username = "")
{
    string _name = System.Net.WebUtility.HtmlEncode(username.Trim());

    if(0 == _name.Length)
    {
        return "操作失敗!";
    }

    Model.dbo.MyUser user = new Model.dbo.MyUser
    {
        name = _name,
        createtime = DateTime.Now
    };

    db.Users.Add(user);
    db.SaveChanges();

    Response.Redirect(Url.Action("Index", "Home"));
    return "";
}

其中,這裏有一個“System.Net.WebUtility.HtmlEncode”,他是相當於之前 MVC 中的 Server.HtmlEncode,對傳過來的參數進行處理,以防止別人傳來一些危險字符,造成數據庫問題。

上面已經不是[HttpGet],而是[HttpPost],說明必須是 Post 方式防問。好的,我們執行一下看看:

這裏寫圖片描述

點擊提交後的執行結果:
這裏寫圖片描述

三、改:
能查看,能增加,那麼就必須能修改了。修改一般要在查的基礎之上。如果不查,是不可能修改的,因爲你不知道修改誰,怎麼確定修改的對象。就像找小姐,你不可能找個長得比較難看的,一般都有一個硬性需求,再找。有時找一個,有時找兩以上。找一個就男女單打,兩個是鬥地主,三個就是麻將。

因爲,爲了以查爲基礎,所以,我們要修改一下 Index 的內容——也就是加一個操作列。

<style type="text/css">
    .tableStyleBorder {margin: 0px auto; margin-top: 30px; border-collapse: collapse; border: 1px solid Black;}
    .tableStyleBorder th, .tableStyleBorder td {min-width: 80px; text-align: center; padding: 8px; border: 1px solid Black;}
</style>

<table class="tableStyleBorder">
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>創建時間</th>
        <th>操作</th>
    </tr>
    @if(0 < ViewBag.userCount)
    {
        @foreach (var item in ViewBag.userList)
        {
    <tr>
        <td>@item.id</td>
        <td>@item.name</td>
        <td>@item.createtime</td>
        <td><a href="/Home/[email protected]">修改</a></td>
    </tr>
        }
    }
    else
    {
    <tr>
        <td colspan="3">沒有數據</td>
    </tr>
    }
</table>

這裏加了一個“<th>操作</th>”和“<td><a href=”/Home/[email protected]”>修改</a></td>”,用這種方式來連接修改頁面。

這裏寫圖片描述

那麼好,萬事俱備,只差修改。我們現在來做修改頁面,我們起名爲“updateInfo”,這個名字可以從 A 標籤中看出來!^^

修改頁,起先要先做個展示頁,之後纔是修改,與“增”操作相似。只不過要在原來的輸入數據的頁面中進行一次查詢相應值,這是爲了如果數據特別多的話,不可能每一個都要進行修改,可能只改幾個的。

先看修改頁面的用戶界面,分爲:視圖(View)與 [HttpGet] 的控制器(Controller)

Views/Home/updateInfo.cshtml:

<div style="margin-top: 30px;">
    @using (Html.BeginForm("updateInfo", "Home", FormMethod.Post))
    {
        <label>姓名:</label>
        string _username = ViewBag.Name;
        @Html.TextBox("username", _username);
        <input type="hidden" id="id" name="id" value="@ViewBag.ID" />
        <input type="submit" id="btnSubmit" name="btnSubmit" />
    }
</div>

我們可以看出從控制器中傳來了兩個值:ViewBag.XXX。因爲在 @Html 中不能直接使用 ViewBag.Name,所以要用“string _username = ViewBag.Name;”嘚瑟一下。

再看看 HomeController 中,我們又加了什麼:

[HttpGet]
public IActionResult updateInfo(int id = 0)
{
    var user = (from u in db.Users
                where u.id == id
                select u).FirstOrDefault();

    if(null == user)
    {
        return RedirectToAction("Error");
    }

    ViewBag.ID = id;
    ViewBag.Name = user.name;

    return View();
}

這裏看到視圖(View)中的 ViewBag 的實現。再看看,我們發現了一個奇怪的一段:

if(null == user)
{
    return RedirectToAction("Error");
}

這一段是通過對數據庫表 Users 查詢後,通過 FirstOrDefault() 方法取到第一個值。但是,如果查詢爲空的話,那麼取到的第一個值就是爲 null,這裏是爲了防止沒有數據的情況下出錯。

這裏稍稍介紹一下,如果在使用 Linq 進行查詢後,沒有用 FirstOrDefault() 的話,來判斷是否有數據,而不是通過與 null 進行對比,而是通過 Count() 方法判斷是否爲 0。

而“return RedirectToAction(“Error”);”就是跳轉的意思,跳轉到同控制器下的 Error 視圖(View)中。而這個視圖,我們可以不用做控制器——就是顯示一行字而已:

Views/Home/Error.cshtml:

<div style="text-align: center;"><h1>頁面錯誤!</h1></div>

整個執行的頁面樣式就是:
這裏寫圖片描述

好現在修改頁面已經做好了。當我們點擊提交時,就應該交由系統來進行修改操作了。這個,與“增”一樣,完全在控制器中執行:

[HttpPost]
public string updateInfo(int id = 0, string username = "")
{
    string _name = System.Net.WebUtility.HtmlEncode(username.Trim());

    var user = (from u in db.Users
                where u.id == id
                select u).FirstOrDefault();

    if (null == user && 0 == _name.Length)
    {
        Response.Redirect(Url.Action("Error", "Home"));
        return "";
    }

    user.name = _name;
    db.SaveChanges();

    Response.Redirect(Url.Action("Index", "Home"));
    return "";
}

我們執行一下。首先,我們在 Index 裏選擇找二條數據,並點擊那一行的“修改”:
這裏寫圖片描述

在進入的修改頁面中,將 123 改成 abc,並點擊“提交”按鈕。
這裏寫圖片描述

之後,系統自動執行並顯示最終結果 ->Index
這裏寫圖片描述

修改操作就這樣子了。

四、刪:
最後一項了,終於到了刪了。刪除也是必要操作,但是是屬於危險性操作,因爲可能整不好數據就沒了。好了,現在我們開始準備刪除操作。

準備與“改”一樣,就是在操作那一列中再加個“刪除”即可:

@{
    ViewData["Title"] = "主頁";
}

<style type="text/css">
    .tableStyleBorder {margin: 0px auto; margin-top: 30px; border-collapse: collapse; border: 1px solid Black;}
    .tableStyleBorder th, .tableStyleBorder td {min-width: 80px; text-align: center; padding: 8px; border: 1px solid Black;}
</style>

<table class="tableStyleBorder">
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>創建時間</th>
        <th>操作</th>
    </tr>
    @if(0 < ViewBag.userCount)
    {
        @foreach (var item in ViewBag.userList)
        {
    <tr>
        <td>@item.id</td>
        <td>@item.name</td>
        <td>@item.createtime</td>
        <td>
            <a href="/Home/[email protected]">修改</a>
            |
            <a href="/Home/[email protected]">刪除</a>
        </td>
    </tr>
        }
    }
    else
    {
    <tr>
        <td colspan="3">沒有數據</td>
    </tr>
    }
</table>

這裏寫圖片描述

從上面,我們能看出來,刪除是調用 delInfo。因爲是刪除,不需要顯示什麼,所以直接在“控制器”(Controller)中進行操作即可,代碼如下:

public string delInfo(int id = 0)
{
    var user = (from u in db.Users
                where u.id == id
                select u).FirstOrDefault();

    if (null == user)
    {
        Response.Redirect(Url.Action("Error", "Home"));
        return "";
    }

    db.Users.Attach(user);
    db.Users.Remove(user);
    db.SaveChanges();

    Response.Redirect(Url.Action("Index", "Home"));
    return "";
}

我們點擊一下第二行的“刪除”看看效果:
這裏寫圖片描述

OK,增刪改查全部完成。有一件需要說明一下。在批量操作時,“db.SaveChanges();”在方法中最好在一批次中,只執行一次,不然會出現死鎖,比如:

foreach(var item in userlist)
{
    item.name = "1111";
}
db.SaveChanges();

千萬不要把 db.SaveChanges() 寫到 foreach{} 裏。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章