2019/0508/Asp.Net_MVC_Model_ADO.NET+Entityframework+LoginMember實作+MVC觀念

#ASP.NET_MVC_Model_ADOnet

首先開個空的mvc專案

然後老師有準備個db demo

然後開始先寫controllers

把ADO會用到的套件using進去

連線資訊放在 組態webconfig 是一種保密方式

更好的方式要在作業系統帳號密碼

或是帳號密碼放在AD統一管理

所以要去webconfig改資料庫存取路徑

|DataDirectory|是相對路徑會自動去app_data找資料庫

Intrgrated Security 是否要帳號密碼

<connectionStrings>
    <add name="dbStudentConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|dbStudent.mdf;Integrated Security=True;"
          providerName="System.Data.SqlClient" />
  </connectionStrings>

相對於資料庫內的帳號密碼會顯示

這邊只有使用者會知道帳號密碼,因為存在作業系統

接著建造資料庫物件

建造在action外側

因為要讓所有action都能用

接著到index actionresult

去撈資料放入dataset物件 (

再放進去datatable物件 ( 資料表

Return view這個 datatable

接著去編輯view讓這個資料能夠顯示

因為是空的view而且也沒套用model模板

所以最上面要人工抓model

然後簡單html排版

利用@razor迴圈抓取資料並顯示

簡單套bootstrap table 瞬間排版 …

如果ftp抓資料下不來可能是在使用就會產生log檔

以下是老師版本步驟 老師有兩個版本的步驟不知道為啥

//05-2 ADO.net使用練習
//05-2-1 將dbStudent.mdb資料庫放入App_Data資料夾
//05-2-2 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//05-2-3 指定控制器名稱為HomeController,並開啟HomeController
//05-2-4 using System.Data、System.Data.SqlClient、System.Configuration
//05-2-5 加入連線設定在Web.config檔裡
//05-2-6 設定Connection與SqlCommand物件
//05-2-7 建立一般方法executeSql()-可傳入SQL字串來輯編資料表
//05-2-8 建立一般方法querySql()-可傳入SQL字串並傳回DataTable物件
//05-2-9 建立Index() Action回傳DataTable資料給View
//05-2-10 建立GET與POST Create Action
//05-2-11 建立POST Delete Action
//05-2-12 在public ActionResult Index()上按右鍵,新增檢視,建立Index View
//05-2-13 進行下列設定:
//        View name:Index
//        Template:Empty (Without model)
//        勾選Use a layout pages
//        按下Add
//05-2-14 撰寫Home/Index View的內容
//05-2-15 在public ActionResult Create()上按右鍵,新增檢視,建立Create View
//05-2-16 進行下列設定:
//        View name:Create
//        Template:Empty (Without model)
//        勾選Use a layout pages
//        按下Add
//05-2-17 撰寫Home/Create View的內容
//05-2-18 執行並測試

不一定所有的系統都具備新增刪除修改

有寫才有

所以我們先寫一個create action

這個是控制create html view頁面使用

在建立一個 create ( 參數 多載

用於將資料存入資料庫

首先將sql語言 寫 insert 放入字串中

在控制資料庫物件做方法(靜態函式?

Cmd.Parameters.AddWithValue

此方法需要給參數與參數來源

記得存入時要打開資料庫存完要關閉資料庫

做完後將資料 傳到 index action

接著做 delete

只要改寫create即可

然後回頭看有很多重複的code

所以…高內聚力低偶合力

建立一般方法

調整架構 把一些重複使用的放在這

以下為調整完後的code

方法為 先直覺寫在 調整會比較好思考

### /03Model_ADOnet/Controllers/HomeController.cs

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

namespace _03Model_ADOnet.Controllers
{
    public class HomeController : Controller
    {
        SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbStudentConnectionString"].ConnectionString);
        SqlCommand Cmd = new SqlCommand();

        //05-2-8 建立一般方法querySql()-可傳入SQL字串並傳回DataTable物件
        private DataTable querySql(string sql)
        {
            SqlDataAdapter adp = new SqlDataAdapter(sql, Conn);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return  ds.Tables[0];
        }

        //05-2-7 建立一般方法executeSql()-可傳入SQL字串來輯編資料表
        private void executeSql(string sql)
        {
            Conn.Open();
            Cmd.Connection = Conn;
            Cmd.CommandText = sql;
            Cmd.ExecuteNonQuery();
            Conn.Close();

           
        }
        //05-2-9 建立Index() Action回傳DataTable資料給View
        public ActionResult Index()
        {
            DataTable dt = querySql("Select * from tStudent");
            return View(dt);
        }

        //05-2-10 建立GET與POST Create Action
        public ActionResult Create()
        {
         
            return View();
        }

        [HttpPost]
        public ActionResult Create(string fStuId, string fName, string fEmail, string fScore)
        {
            string sql = "insert into tStudent values(@fStuId,@fName,@fEmail,@fScore)";
            Cmd.Parameters.AddWithValue("@fStuId", fStuId);
            Cmd.Parameters.AddWithValue("@fName", fName);
            Cmd.Parameters.AddWithValue("@fEmail", fEmail);
            Cmd.Parameters.AddWithValue("@fScore", fScore);

            executeSql(sql);

            return RedirectToAction("Index");
        }

        //05-2-11 建立POST Delete Action
        public ActionResult Delete(string id)
        {
            string sql = "delete from tstudent where fStuId=@fStuId";
            Cmd.Parameters.AddWithValue("@fStuId", id);

            executeSql(sql);

            return RedirectToAction("Index");
        }

    }
}

###以下為老師步驟

//05-2-6 設定Connection與SqlCommand物件
//05-2-7 建立一般方法executeSql()-可傳入SQL字串來輯編資料表
//05-2-8 建立一般方法querySql()-可傳入SQL字串並傳回DataTable物件
//05-2-9 建立Index() Action回傳DataTable資料給View
//05-2-10 建立GET與POST Create Action
//05-2-11 建立POST Delete Action
//05-2-12 在public ActionResult Index()上按右鍵,新增檢視,建立Index View
//05-2-13 進行下列設定:
//        View name:Index
//        Template:Empty (Without model)
//        勾選Use a layout pages
//        按下Add
//05-2-14 撰寫Home/Index View的內容

沒有model是把資料庫擺在 app data 裡面

藉由 webing 去調用 增加資安性與物件導向重複利用性

接著編輯 creat.cshtml

這邊會示範bs3如何做表單form

首先要設定傳送方式與動作(url請求傳送的封包內容

<form method="post" action="@Url.Action("Create")">

表單到這邊就結束了 以下示範bs3排版

###一樣的重點

Id給前端用的

name給後端用的記得要簡單繫結與後端參數相同名稱

Type給input用的html5

Class給bs用的

這裡應用到 label for 這個??

可以讓區域點選 這方面可能還要看一下

喔喔原來是 htmltag自帶的功能for對應的是id

###Bs網格系統要空格要用 offset後面在接空幾格

接著最後用@razor做連結將顯示頁面與新增頁面鏈結

回到index

做刪除的@razor 這邊跟上面類似但比較麻煩是

Helper裡面傳的參數比較複雜不是傳頁面

而是用razor寫的要帶在url裡面傳到後端的指令

##以下為老師程式碼

###model

#MVC連接資料庫db兩大做法 04Model_EF

##1.Ado.net 蟑螂

.net 1.0 就有了

###03Model_ADOnet/Controllers/HomeController.cs

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

namespace _03Model_ADOnet.Controllers
{
    public class HomeController : Controller
    {
        SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbStudentConnectionString"].ConnectionString);
        SqlCommand Cmd = new SqlCommand();

        //05-2-8 建立一般方法querySql()-可傳入SQL字串並傳回DataTable物件
        private DataTable querySql(string sql)
        {
            SqlDataAdapter adp = new SqlDataAdapter(sql, Conn);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return  ds.Tables[0];
        }

        //05-2-7 建立一般方法executeSql()-可傳入SQL字串來輯編資料表
        private void executeSql(string sql)
        {
            Conn.Open();
            Cmd.Connection = Conn;
            Cmd.CommandText = sql;
            Cmd.ExecuteNonQuery();
            Conn.Close();

           
        }
        //05-2-9 建立Index() Action回傳DataTable資料給View
        public ActionResult Index()
        {
            DataTable dt = querySql("Select * from tStudent");
            return View(dt);
        }

        //05-2-10 建立GET與POST Create Action
        public ActionResult Create()
        {
         
            return View();
        }

        [HttpPost]
        public ActionResult Create(string fStuId, string fName, string fEmail, string fScore)
        {
            string sql = "insert into tStudent values(@fStuId,@fName,@fEmail,@fScore)";
            Cmd.Parameters.AddWithValue("@fStuId", fStuId);
            Cmd.Parameters.AddWithValue("@fName", fName);
            Cmd.Parameters.AddWithValue("@fEmail", fEmail);
            Cmd.Parameters.AddWithValue("@fScore", fScore);

            executeSql(sql);

            return RedirectToAction("Index");
        }

        //05-2-11 建立POST Delete Action
        public ActionResult Delete(string id)
        {
            string sql = "delete from tstudent where fStuId=@fStuId";
            Cmd.Parameters.AddWithValue("@fStuId", id);

            executeSql(sql);

            return RedirectToAction("Index");
        }

    }
}

###老師步驟

//05-2 ADO.net使用練習
//05-2-1 將dbStudent.mdb資料庫放入App_Data資料夾
//05-2-2 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//05-2-3 指定控制器名稱為HomeController,並開啟HomeController
//05-2-4 using System.Data、System.Data.SqlClient、System.Configuration
//05-2-5 加入連線設定在Web.config檔裡
//05-2-6 設定Connection與SqlCommand物件
//05-2-7 建立一般方法executeSql()-可傳入SQL字串來輯編資料表
//05-2-8 建立一般方法querySql()-可傳入SQL字串並傳回DataTable物件
//05-2-9 建立Index() Action回傳DataTable資料給View
//05-2-10 建立GET與POST Create Action
//05-2-11 建立POST Delete Action
//05-2-12 在public ActionResult Index()上按右鍵,新增檢視,建立Index View
//05-2-13 進行下列設定:
//        View name:Index
//        Template:Empty (Without model)
//        勾選Use a layout pages
//        按下Add
//05-2-14 撰寫Home/Index View的內容

###/03Model_ADOnet/Views/Home/Create.cshtml

@{
    ViewBag.Title = "Create";
}

<h2>新增學生資料</h2>
<form method="post" action="@Url.Action("Create")">
    <div class="form-horizontal">
        <hr />
        <div class="form-group">
            <label class="control-label col-md-3" for="fStuId">學號</label>
            <div class=" col-md-9">
                <input id="fStuId" name="fStuId" type="text" class="form-control" required />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-3" for="fName">姓名</label>
            <div class=" col-md-9">
                <input id="fName" name="fName" type="text" class="form-control" required />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-3" for="fEmail">E-Mail</label>
            <div class=" col-md-9">
                <input id="fEmail" name="fEmail" type="text" class="form-control" required />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-3" for="fScore">成績</label>
            <div class=" col-md-9">
                <input id="fScore" name="fScore" type="text" class="form-control" required />
            </div>
        </div>

        <div class="form-group">
           
            <div class="col-md-offset-3 col-md-9">
                <input id="Submit1" type="submit" value="送出" class="btn btn-primary" />
            </div>
        </div>
    </div>
    <div>
        @Html.ActionLink("返回列表","Index")
    </div>
</form>

###/03Model_ADOnet/Views/Home/Index.cshtml

@using System.Data;
@model System.Data.DataTable

@{
    ViewBag.Title = "學生列表";
}

<h2>學生列表</h2>

<div>
    @Html.ActionLink("新增一筆資料", "Create")
</div>
<table class="table table-striped">
    <tr>
        <th>學號</th>
        <th>姓名</th>
        <th>信箱</th>
        <th>成績</th>
        <th>刪除</th>
    </tr>
    @foreach (DataRow row in Model.Rows)
    {
    <tr>
        <td>@row["fStuId"]</td>
        <td>@row["fName"]</td>
        <td>@row["fEmail"]</td>
        <td>@row["fScore"]</td>
        <td>@Html.ActionLink("刪除","Delete",new { id=row["fStuId"]},new { @class="btn btn-danger", onclick="return confirm('確定刪除嗎?')"})</td>
    </tr>
    }
</table>

##2.Entity framework

Webform

則是datasource control 控制項

##以下開始講 EBTITY FRAMEWORK

開新專案

##LINQ 語法sql的倒裝句

Sql

selec * from

Where

Groud by

Having

Oderby

但linq是從from

### Lanbda方法可以不用寫那麼長的linq

就像view要用到@razor所以講一樣

###以下範例為高雄銀行考題

首先宣告一個

一般方法

宣告 陣列 成績

題目是從大到小排

通常使用氣泡排序

這邊使用EBTITY FRAMEWORK

Linq語法 的 擴充表示法 Lambda

Var show = Score.orderbydescending(s=>s);

呼叫內建函數來用 ( 泛型 物件 上面那個

但高雄銀行是要把內建函數內容寫出來

接著迴圈一個一個讀出來

Linq大部分都在操控資料

例如 排序 抓取位址資料 常用的就會做成擴充方法lambda

如果要用的功能沒有就要自己寫

用pre linq 寫起來就會比較長

Linq 查詢運算式

原生sql select * table order by score desc // dml

物件 result=

from資料表名稱in集合

where條件

orderby資料表名稱descending

select 資料表名稱

感覺原生要先學熟在學擴充 …

擴充方法加總

Result.sum()

C#有些擴充語言可以做到某些功能但某些功能沒有內建可能R有JAVA有

看那個語言適合做甚麼可以做什麼不可以做甚麼

##接著模擬登入 LoginMember

建立一個model但是在controllers裡面的類別檔案

Codefirst?? 自動建立pk ? 後面會講?

沒有規定model一定要放在models資料夾

也沒有規定 controller一定要放在controllers資料夾

只差在namespace放置位置跟using引入

在回到homecontroller.cs

Arraylist new ???? 物件陣列建構子 ( 可以一次new一堆物件

然後建構裡面的物件

model在controllers裡面的member.cs內

然後也是pre linq 跟lambda linq兩種方式去操作這些資料

### 運算要用c#的語法不能用sql語法

###以下為老師程式碼

###model

###/04Model_EF/Controllers/Member.cs

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

namespace _04Model_EF.Controllers
{
    public class Member
    {
        public string UId { get; set; }
        public string Pwd { get; set; }
        public string Name { get; set; }
    }
}

###04Model_EF/Controllers/HomeController.cs

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

namespace _04Model_EF.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        //04-1-3 建立一般方法ShowAryDesc()-整數陣列遞減排序
        public string ShowArrayDesc()
        {
            int[] score = { 78, 99, 20, 90, 66, 100, 75, 45, 26 };

            //SQL DML
            //Select * from score order by s desc
            //Linq查詢運算式
            var result = from s in score
                         orderby s descending
                         select s;


            //Linq擴充方法
            //用Lambda表示法撰寫
            //var result = score.OrderByDescending(s => s);  //大到小(遞減)
            //var result = score.OrderBy(s => s);  //小到大(遞增)


            string show ="";
            foreach(var s in result)
            {
                show += s + ",";
            }

            return show+ "總和:"+result.Sum();//使用Linq的Sum方法進行加總
        }

        //04-1-9 在HomeController中建立一般方法LoginMember()-整數陣列遞增排序
        public string LoginMember(string uid, string pwd)
        {
            Member[] members = new Member[] 
            {
                new Member{ UId="tom",Pwd="123",Name="湯姆"},
                new Member{ UId="jobs",Pwd="456",Name="賈伯斯"},
                new Member{ UId="mary",Pwd="789",Name="瑪莉"}
            };

            //SQL DML
            //Select * from members where UId=uid and Pwd=pwd
            //Linq查詢運算式
            //var result = (from m in members
            //              where m.UId == uid && m.Pwd == pwd
            //              select m).FirstOrDefault();

            string show = "";
            //Linq擴充方法
            //用Lambda表示法撰寫
            var result = members.Where(m => m.UId == uid && m.Pwd == pwd).FirstOrDefault();

            if (result == null)
                show = "帳號或密碼有誤!!";
            else
                show = result.Name + "歡迎光臨";

            return show;



        }



    }
}

###老師步驟

//04-1 Linq練習
//04-1-1 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//04-1-2 指定控制器名稱為HomeController,並開啟HomeController
//04-1-3 建立一般方法ShowAryDesc()-整數陣列遞減排序
//04-1-4 執行並測試 http://localhost:53468/Home/ShowAryDesc (port可能不同)
//04-1-7 在Controllers資料夾上按右鍵,選擇加入,新增項目,程式碼,選擇類別,名稱鍵入Member.cs
//04-1-8 在Member class中輸入下列欄位
//04-1-9 在HomeController中建立一般方法LoginMember()-整數陣列遞增排序
//04-1-10 執行並測試 http://localhost:53468/Home/LoginMember?uid=tom&pwd=123 (port可能不同)

##接著建立資料庫?? 04Model_EF/北風資料庫

Model右鍵

北風資料庫 ( 微軟公開練習資料進銷存系統 ( 老師這個版本是簡化過的

純淨態類別永久性儲存類別圖 相對應的是 存在記憶體內的暫存

導讀model了解內容

實際上這些model在做ADO時自動成為class

###Db first 所以會出現一些自動出現的東西 例如關聯等等

Model用controller操控

要講linq操作

這次是真的要從資料庫讀

剛剛都是把資料放在專案檔案內

Mvc方式是透過model去存取資料庫

新增一個 linqController.cs

做db物件

然後新增一個 string showenployee()

用pre linq 取資料

然後再用 lambda linq 取資料

兩種方式

然後想要秀在view上面的話 老師這邊是套版view

###很常犯的錯誤 記得 return 後面 view() 參數要回傳資料回去不然看不到

##以下為老師程式碼

###04Model_EF/Models/

###04Model_EF/Views/Linq/Index.cshtml

@model IEnumerable<_04Model_EF.Models.員工>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.姓名)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.名)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.職稱)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.稱呼)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.出生日期)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.雇用日期)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.地址)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.城市)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.行政區)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.區域號碼)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.國家地區)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.電話號碼)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.內部分機號碼)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.相片)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.附註)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.主管)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.姓名)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.名)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.職稱)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.稱呼)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.出生日期)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.雇用日期)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.地址)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.城市)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.行政區)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.區域號碼)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.國家地區)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.電話號碼)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.內部分機號碼)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.相片)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.附註)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.主管)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.員工編號 }) |
            @Html.ActionLink("Details", "Details", new { id=item.員工編號 }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.員工編號 })
        </td>
    </tr>
}

</table>

###04Model_EF/Controllers/LinqController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using _04Model_EF.Models;

namespace _04Model_EF.Controllers
{
    public class LinqController : Controller
    {
        NorthwindEntities db = new NorthwindEntities();

        // GET: Linq
        public ActionResult Index()
        {
            //SQL DML
            //select * from 員工
            //Linq查詢運算式
            //var result = from E in db.員工
            //             select E;

            string show = "";
            //Linq擴充方法
            //用Lambda表示法撰寫
            var result = db.員工.ToList();

   
            return View(result);
        }

        public string ShowEmployee()
        {
            //SQL DML
            //select * from 員工
            //Linq查詢運算式
            //var result = from E in db.員工
            //             select E;
            
            string show = "";
            //Linq擴充方法
            //用Lambda表示法撰寫
            var result = db.員工;


            foreach(var E in result)
            {
                show += "工號:"+E.員工編號+" 姓名:"+E.姓名+" 職稱:"+E.職稱+"<br />";
            }

            return show;
        }

    }
}

##老師步驟

//04-2 Entity FrameWork
//04-2-1 建立NorthWind.mdb資料庫Model
//       在Models上按右鍵,選擇加入,新增項目,資料,ADO.NET實體資料模型
//       來自資料庫的EF Designer
//       連接NorthWind.mdf資料庫,連線名稱不修改,按下一步按鈕
//       選擇Entity Framework 6.x, 按下一步按鈕
//       資料表"全選", 按完成鈕
//       若跳出詢問方法按確定鈕
//04-2-3 在專案上按右鍵,建置
//04-2-4 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//04-2-5 指定控制器名稱為LinqController,並開啟LinqController
//04-2-6 using _04EF.Models
//04-2-7 於LinqController建立DB物件
//04-2-8 建立一般方法ShowEmployee()-查詢所有員工記錄
//04-2-9 執行並測試 http://localhost:53468/Linq/ShowEmployee (port可能不同)
//04-2-10 建立一般方法Index() Action-查詢所有員工記錄
//04-2-11 進行下列設定:建立View
//        View name:Index
//        Template:List
//        Model class:員工(_04Ef.Models)
//        Data context class:NorthwindEntities(_04Ef.Models)
//        勾選Use a layout pages
//        按下Add
//04-2-12執行並測試 http://localhost:53468/Linq/Index (port可能不同)

#在model裡面建立驗證功能

接著dbstudent.mdf建立model

Webform時用驗證器控制項

Mvc時

寫在model或寫在view或寫在controller

這邊簡單介紹後面會複雜介紹 …

Dbfister時很多程式碼物件會自動產生要相信做db的人

回到model tStudent.cs

Using sysyem.componentmodel

即可用

[Displayname(“”)]

即便是db產生的model也可以在model檔案裏面去修改model

驗證必填 [required(ErrorMessage =”學號不可空白”)]

驗證信箱 [EmailAddress(ErrorMessage =”信箱格式有誤”)]

驗證範圍 [Range(0,100,ErrorMessage =”信箱格式有誤”)]

好了model弄好了

新增一個 ValidationController.cs

做model驗證示範的view的controller

首先 加入資料庫

在把資料庫物件丟到變數

在return到view

新增一個view範本即可

接著稍微修改這個範本產生出來的東西

好了之後我們只實作creat 所以只留delete

回到ValidationController.cs

建置一個 actionResult Create()

連接view

[httpPost]

actionResult Create(tSttudent stu) pk

做資料回傳資料庫的動作

首先先判定驗證通不通過 利用

Modelstate.isvalid

才可以

將tstudent stu加入 db中

然後儲存結果

傳回redirecttoaction (“index”)

如果沒有驗證成功則return View(stu);

接著實作delete

新增一個actionresult

傳入要delete的pk

然後利用物件去查詢它然後刪除

確定刪除

回到index

###老師程式碼如下

###04Model_EF/App_Data/dbStudent.mdf

##04Model_EF/Models/tStudent.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     這個程式碼是由範本產生。
//
//     對這個檔案進行手動變更可能導致您的應用程式產生未預期的行為。
//     如果重新產生程式碼,將會覆寫對這個檔案的手動變更。
// </auto-generated>
//------------------------------------------------------------------------------

namespace _04Model_EF.Models
{
    using System;
    using System.Collections.Generic;
    //04-2-5 using System.ComponentModel 及 System.ComponentModel.DataAnnotations
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;

    //04-2-6 在原程式中加入驗證功能標籤 
    public partial class tStudent
    {
        [DisplayName("學號")]
        [Required(ErrorMessage ="學號不可空白")]
        public string fStuId { get; set; }

        [DisplayName("姓名")]
        [Required(ErrorMessage = "姓名不可空白")]
        public string fName { get; set; }

        [DisplayName("信箱")]
        [Required(ErrorMessage = "信箱不可空白")]
        [EmailAddress(ErrorMessage = "信箱格式有誤")]
        public string fEmail { get; set; }

        [DisplayName("成績")]
        [Range(0,100, ErrorMessage = "請填入0~100的整數")]
        public Nullable<int> fScore { get; set; }
    }
}

###04Model_EF/Controllers/ValidationController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//04-3-8 using _04EF.Models
using _04Model_EF.Models;

namespace _04Model_EF.Controllers
{
    public class ValidationController : Controller
    {
        //04-3-9 於VilidationController建立DB物件,並撰寫Index、Create、Delete的Action
        dbStudentEntities db = new dbStudentEntities();

        // GET: Validation
        public ActionResult Index()
        {
            var student = db.tStudent.ToList();
            return View(student);
        }

        public ActionResult Create()
        {
           
            return View();
        }

        [HttpPost]
        public ActionResult Create(tStudent stu)
        {
            if (ModelState.IsValid)
            {
                db.tStudent.Add(stu);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(stu);
        }

        public ActionResult Delete(string id)
        {
            var stuID = db.tStudent.Where(s=>s.fStuId==id).FirstOrDefault();
            db.tStudent.Remove(stuID);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}

###04Model_EF/Views/Validation/Create.cshtml

@model _04Model_EF.Models.tStudent

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>tStudent</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.fStuId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fStuId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fStuId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.fName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.fEmail, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fEmail, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fEmail, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.fScore, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fScore, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fScore, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

###04Model_EF/Views/Validation/Index.cshtml

@model IEnumerable<_04Model_EF.Models.tStudent>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.fStuId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fEmail)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fScore)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.fStuId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fEmail)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fScore)
        </td>
        <td>
            @*@Html.ActionLink("Edit", "Edit", new { id = item.fStuId }) |
            @Html.ActionLink("Details", "Details", new { id = item.fStuId }) |*@
            @Html.ActionLink("刪除", "Delete", new { id = item.fStuId },new { onclick="return confirm('確定刪除嗎?')"})
        </td>
    </tr>
}

</table>

Last updated