> For the complete documentation index, see [llms.txt](https://johch3n611u.gitbook.io/c50108/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://johch3n611u.gitbook.io/c50108/ju-li-cheng-bei/201905/2019-0516.md).

# 2019/0516/BS form&驗證+JQ驗證 & MVC\_CRUD(CU)

\#Bootstrap

接續昨天card

可以套其他組件

學框架要懂舉一反三

積木在那裏了堆成怎樣就看各人

{% embed url="<https://bootstrap.hexschool.com/docs/4.2/components/forms/>" %}

接著

### ##bs form&#xD; class

Webform一頁只能有一個form標籤就是最外層那層form且屬性server就是在伺服器執行

![](/files/-Lf-HFEf43o9Ln-LETlS)

但其實pre html 一頁可以有很多 form

友善介面 input 善用 label for id & placeholder&#x20;

#### ##Class keyword&#xD;

Form-group

Form-control

Form-text

Text-muted

btn

btn-secondary

form-check

form-check-input

#### ###/RWD/17Form.html&#xD;

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title></title>

    <link href="Content/bootstrap.min.css" rel="stylesheet" />

    <link href="MyStyle.css" rel="stylesheet" />
</head>
<body>
    <form>
        <div class="container">
            <div class="form-group">
                <label for="email">Email:</label>
                <input id="email" type="email" class="form-control" placeholder="Enter email..." required />
                <small class="form-text text-muted">忘記帳號</small>
            </div>
            <div class="form-group">
                <label for="pwd">Password:</label>
                <input id="pwd" type="password" class="form-control" placeholder="Password" required />
            </div>
            <div class="form-group form-check">
                <input id="remember" type="checkbox" class="form-check-input" />
                <label for="remember">記住我</label>
            </div>
            <input id="Submit1" type="submit" value="submit" class="btn btn-secondary" />

        </div>
    </form>
</body>
</html>

```

![](/files/-Lf-Hl-SW_8s-PE-y9B2)

以上為上下排較制式

接著嘗試左右排

要配合gridsystem

在container內做就會遷就container的大小

#### ##keyword&#xD;

form-row

以前還要多一個div做col現在可以在 form-group那層直接col

col-md-6

以前還要每個都下 form-row

現在只要讓div在同一階層他就會自動判斷為 form-row ?

只要是form 裡面的物件 就用 form-group 然後 form-control

然後用 form-row橫排或不寫 直接直排

#### ##接著將欄位名稱與欄位並排&#xD;

#### ###Form-group 直接當 row 底下的就都變 col 但input要用div包住下col ??   ((( legend 也是一個 div 的感覺&#xD;

Col-form-label

Form-label-lg  ( 字就會變大 ?

#### ##題外話 控制項 ?&#xD;

{% embed url="<https://www.google.com/search?q=%E6%8E%A7%E5%88%B6%E9%A0%85&rlz=1C1GCEU_zh-TWTW835TW836&oq=%E6%8E%A7%E5%88%B6%E9%A0%85&aqs=chrome..69i57j69i61j69i65l3j69i61.3251j0j4&sourceid=chrome&ie=UTF-8>" %}

#### ##題外話 Html tag  fieldset  legend&#xD;

{% embed url="<https://www.google.com/search?q=fieldset+legend&oq=fieldset+legend&aqs=chrome..69i57.512j0j1&sourceid=chrome&ie=UTF-8>" %}

\###/RWD/17Form.html

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title></title>

    <link href="Content/bootstrap.min.css" rel="stylesheet" />

    <link href="MyStyle.css" rel="stylesheet" />
</head>
<body>


    <form>
        <div class="container">
            <div class="form-group">
                <label for="email">Email:</label>
                <input id="email" type="email" class="form-control" placeholder="Enter email..." required />
                <small class="form-text text-muted">忘記帳號</small>
            </div>
            <div class="form-group">
                <label for="pwd">Password:</label>
                <input id="pwd" type="password" class="form-control" placeholder="Password" required />
            </div>
            <div class="form-group form-check">
                <input id="remember" type="checkbox" class="form-check-input" />
                <label for="remember">記住我</label>
            </div>
            <input id="Submit1" type="submit" value="submit" class="btn btn-secondary" />

        </div>
    </form>

    <hr />

    <form>
        <div class="container">
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="email">Email:</label>
                    <input id="email" type="email" class="form-control" placeholder="Enter email..." required />
                    <small class="form-text text-muted">忘記帳號</small>
                </div>
                <div class="form-group col-md-6">
                    <label for="pwd">Password:</label>
                    <input id="pwd" type="password" class="form-control" placeholder="Password" required />
                </div>

            </div>
            <div class="form-group">
                <label for="Address">Address:</label>
                <input id="Address" type="text" class="form-control" placeholder="Address" required />
            </div>


            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="City">City:</label>
                    <input id="City" type="text" class="form-control" placeholder="City" />
                </div>
                <div class="form-group col-md-4">
                    <label for="State">State:</label>
                    <select id="State" class="form-control">
                        <option>Choose...</option>
                        <option>111</option>
                        <option>222</option>
                    </select>
                </div>
                <div class="form-group  col-md-2">
                    <label for="abc">abc:</label>
                    <input id="abc" type="text" class="form-control" placeholder="abc" />
                </div>
            </div>
            <div class="form-group form-check">
                <input id="Agree" type="checkbox" class="form-check-input" />
                <label for="Agree">Agree</label>
            </div>

            <input id="Submit1" type="submit" value="submit" class="btn btn-secondary" />

        </div>
    </form>

    <hr />

    <form>
        <div class="container">
            <div class="form-group row">
                <label for="email" class="col-sm-3">Email:</label>
                <div class="col-sm-9">
                    <input id="email" type="email" class="form-control" placeholder="Enter email..." required />
                </div>
            </div>
            <div class="form-group row">
                <label for="pwd" class="col-sm-3 col-form-label col-form-label-lg">Password:</label>
                <div class="col-sm-9">
                    <input id="pwd" type="password" class="form-control form-control-lg" placeholder="Password" required />
                </div>
            </div>

            <fieldset class="form-group">
                <div class="row">
                    <legend class="col-form-label col-sm-3">性別</legend>
                    <div class="col-sm-9">
                        <div class="form-check">
                            <input id="male" type="radio" name="gender" />
                            <label for="male">男</label>
                        </div>
                        <div class="form-check">
                            <input id="female" type="radio" name="gender" />
                            <label for="female">女</label>
                        </div>
                    </div>
                </div>
            </fieldset>

            <div class="form-group form-check">
                <input id="remember" type="checkbox" class="form-check-input" />
                <label for="remember">記住我</label>
            </div>
            <input id="Submit1" type="submit" value="submit" class="btn btn-secondary" />

        </div>
    </form>

</body>
</html>

```

![](/files/-Lf-IWfumceoxDh0Ul49)

### ##接著form實例??&#xD;

form-inline

sr-only ( lable會不見 ?? ( 視障者專用 ?

<https://segmentfault.com/q/1010000003007829>

原則 form-control 一定會有 其他都是扛拜 ??

Form-check

Form-check-input

Form-check-lable

#### ### /RWD/18Form-2.html&#xD;

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title></title>

    <link href="Content/bootstrap.min.css" rel="stylesheet" />

    <link href="MyStyle.css" rel="stylesheet" />
</head>
<body>


    <div class="card bg-light">
        <div class="container">

            <form class="form-inline">
                <label for="email" class="sr-only">Email:</label>
                <input id="email" type="email" class="form-control mb-2 mr-sm-2" placeholder="Enter email..." required />



                <label for="pwd" class="sr-only">Password:</label>
                <input id="pwd" type="password" class="form-control mb-2 mr-sm-2" placeholder="Password" required />

                <div class="form-check mb-2 mr-sm-2">
                    <input id="remember" type="checkbox" class="form-check-input" />
                    <label for="remember" class="form-check-label">記住我</label>
                </div>
                <input id="Submit1" type="submit" value="submit" class="btn btn-secondary mb-2" />
            </form>
        </div>
    </div>

    <hr />
    <div class="container">

        <div class="textcenter">
            <h1 class="text-center">My Website</h1>
        </div>


        <div class="row">
            <div class="col-2 col-md-4 col-sm-6">
                台灣高等法院審理「W飯店女子命案」，今天做出更一審判決，認為朱家龍等人轉讓藥品與女子死亡無相當因果關係，依藥事法轉讓偽藥或禁藥罪，改判朱2年10月徒刑。


                土豪哥朱家龍（前左）被控「W飯店女模案件」。（中央社／資料照）
                更多
                「土豪哥」朱家龍被控於民國105年12月2日訂房入住W Hotel，邀約友人洪聖晏、蔡逸學舉辦毒品派對，另邀郭姓被害女子等人參加，並提供大批毒軟糖、毒梅片同歡，導致郭女於12月7日因用毒過量身亡。

                朱家龍4月初在高院更一審就W飯店命案庭做無罪答辯，強調對死者死亡結果感到抱歉，他遭押2年多，請求法官讓他交保回家向父母懺悔。他在庭上指出，對自己之前吸毒玩樂感到後悔，也對死者死亡結果感到遺憾及抱歉，已和死者家屬達成和解，法律上他應負的責任不會逃避，但他已遭押2年多，也2年多沒看到父母，希望法官能讓他交保，讓他回家向父母認錯及懺悔，他會記取這次教訓，不會再發生憾事。

                朱家龍律師表示，朱家龍已和郭女家屬達成和解，和解金也已全數匯款賠償完畢，但並未透露金額。

                蔡逸學及洪聖晏也做無罪答辯；洪聖晏表示，已與死者家屬和解，他會盡力去彌補及贖罪，過兩天就是清明節，之前奶奶過世，他都沒去上香，希望法官讓他具保停押。

                一、二審依藥事法轉讓偽藥致人於死罪判朱家龍10年徒刑；蔡逸學、洪聖晏各被判刑10年、10年6月。最高法院將朱家龍、蔡逸學、洪聖晏所涉部分發回高院更審，高院更一審今天宣判。
                台灣高等法院審理「W飯店女子命案」，今天做出更一審判決，認為朱家龍等人轉讓藥品與女子死亡無相當因果關係，依藥事法轉讓偽藥或禁藥罪，改判朱2年10月徒刑。


                土豪哥朱家龍（前左）被控「W飯店女模案件」。（中央社／資料照）
                更多
                「土豪哥」朱家龍被控於民國105年12月2日訂房入住W Hotel，邀約友人洪聖晏、蔡逸學舉辦毒品派對，另邀郭姓被害女子等人參加，並提供大批毒軟糖、毒梅片同歡，導致郭女於12月7日因用毒過量身亡。

                朱家龍4月初在高院更一審就W飯店命案庭做無罪答辯，強調對死者死亡結果感到抱歉，他遭押2年多，請求法官讓他交保回家向父母懺悔。他在庭上指出，對自己之前吸毒玩樂感到後悔，也對死者死亡結果感到遺憾及抱歉，已和死者家屬達成和解，法律上他應負的責任不會逃避，但他已遭押2年多，也2年多沒看到父母，希望法官能讓他交保，讓他回家向父母認錯及懺悔，他會記取這次教訓，不會再發生憾事。

                朱家龍律師表示，朱家龍已和郭女家屬達成和解，和解金也已全數匯款賠償完畢，但並未透露金額。

                蔡逸學及洪聖晏也做無罪答辯；洪聖晏表示，已與死者家屬和解，他會盡力去彌補及贖罪，過兩天就是清明節，之前奶奶過世，他都沒去上香，希望法官讓他具保停押。

                一、二審依藥事法轉讓偽藥致人於死罪判朱家龍10年徒刑；蔡逸學、洪聖晏各被判刑10年、10年6月。最高法院將朱家龍、蔡逸學、洪聖晏所涉部分發回高院更審，高院更一審今天宣判。
            </div>
            <div class="col-7 col-md-4 col-sm-6">
                台灣高等法院審理「W飯店女子命案」，今天做出更一審判決，認為朱家龍等人轉讓藥品與女子死亡無相當因果關係，依藥事法轉讓偽藥或禁藥罪，改判朱2年10月徒刑。


                土豪哥朱家龍（前左）被控「W飯店女模案件」。（中央社／資料照）
                更多
                「土豪哥」朱家龍被控於民國105年12月2日訂房入住W Hotel，邀約友人洪聖晏、蔡逸學舉辦毒品派對，另邀郭姓被害女子等人參加，並提供大批毒軟糖、毒梅片同歡，導致郭女於12月7日因用毒過量身亡。

                朱家龍4月初在高院更一審就W飯店命案庭做無罪答辯，強調對死者死亡結果感到抱歉，他遭押2年多，請求法官讓他交保回家向父母懺悔。他在庭上指出，對自己之前吸毒玩樂感到後悔，也對死者死亡結果感到遺憾及抱歉，已和死者家屬達成和解，法律上他應負的責任不會逃避，但他已遭押2年多，也2年多沒看到父母，希望法官能讓他交保，讓他回家向父母認錯及懺悔，他會記取這次教訓，不會再發生憾事。

                朱家龍律師表示，朱家龍已和郭女家屬達成和解，和解金也已全數匯款賠償完畢，但並未透露金額。

                蔡逸學及洪聖晏也做無罪答辯；洪聖晏表示，已與死者家屬和解，他會盡力去彌補及贖罪，過兩天就是清明節，之前奶奶過世，他都沒去上香，希望法官讓他具保停押。

                一、二審依藥事法轉讓偽藥致人於死罪判朱家龍10年徒刑；蔡逸學、洪聖晏各被判刑10年、10年6月。最高法院將朱家龍、蔡逸學、洪聖晏所涉部分發回高院更審，高院更一審今天宣判。
                台灣高等法院審理「W飯店女子命案」，今天做出更一審判決，認為朱家龍等人轉讓藥品與女子死亡無相當因果關係，依藥事法轉讓偽藥或禁藥罪，改判朱2年10月徒刑。


                土豪哥朱家龍（前左）被控「W飯店女模案件」。（中央社／資料照）
                更多
                「土豪哥」朱家龍被控於民國105年12月2日訂房入住W Hotel，邀約友人洪聖晏、蔡逸學舉辦毒品派對，另邀郭姓被害女子等人參加，並提供大批毒軟糖、毒梅片同歡，導致郭女於12月7日因用毒過量身亡。

                朱家龍4月初在高院更一審就W飯店命案庭做無罪答辯，強調對死者死亡結果感到抱歉，他遭押2年多，請求法官讓他交保回家向父母懺悔。他在庭上指出，對自己之前吸毒玩樂感到後悔，也對死者死亡結果感到遺憾及抱歉，已和死者家屬達成和解，法律上他應負的責任不會逃避，但他已遭押2年多，也2年多沒看到父母，希望法官能讓他交保，讓他回家向父母認錯及懺悔，他會記取這次教訓，不會再發生憾事。

                朱家龍律師表示，朱家龍已和郭女家屬達成和解，和解金也已全數匯款賠償完畢，但並未透露金額。

                蔡逸學及洪聖晏也做無罪答辯；洪聖晏表示，已與死者家屬和解，他會盡力去彌補及贖罪，過兩天就是清明節，之前奶奶過世，他都沒去上香，希望法官讓他具保停押。

                一、二審依藥事法轉讓偽藥致人於死罪判朱家龍10年徒刑；蔡逸學、洪聖晏各被判刑10年、10年6月。最高法院將朱家龍、蔡逸學、洪聖晏所涉部分發回高院更審，高院更一審今天宣判。
            </div>
            <div class="col-3 col-md-4">
                台灣高等法院審理「W飯店女子命案」，今天做出更一審判決，認為朱家龍等人轉讓藥品與女子死亡無相當因果關係，依藥事法轉讓偽藥或禁藥罪，改判朱2年10月徒刑。


                土豪哥朱家龍（前左）被控「W飯店女模案件」。（中央社／資料照）
                更多
                「土豪哥」朱家龍被控於民國105年12月2日訂房入住W Hotel，邀約友人洪聖晏、蔡逸學舉辦毒品派對，另邀郭姓被害女子等人參加，並提供大批毒軟糖、毒梅片同歡，導致郭女於12月7日因用毒過量身亡。

                朱家龍4月初在高院更一審就W飯店命案庭做無罪答辯，強調對死者死亡結果感到抱歉，他遭押2年多，請求法官讓他交保回家向父母懺悔。他在庭上指出，對自己之前吸毒玩樂感到後悔，也對死者死亡結果感到遺憾及抱歉，已和死者家屬達成和解，法律上他應負的責任不會逃避，但他已遭押2年多，也2年多沒看到父母，希望法官能讓他交保，讓他回家向父母認錯及懺悔，他會記取這次教訓，不會再發生憾事。

                朱家龍律師表示，朱家龍已和郭女家屬達成和解，和解金也已全數匯款賠償完畢，但並未透露金額。

                蔡逸學及洪聖晏也做無罪答辯；洪聖晏表示，已與死者家屬和解，他會盡力去彌補及贖罪，過兩天就是清明節，之前奶奶過世，他都沒去上香，希望法官讓他具保停押。

                一、二審依藥事法轉讓偽藥致人於死罪判朱家龍10年徒刑；蔡逸學、洪聖晏各被判刑10年、10年6月。最高法院將朱家龍、蔡逸學、洪聖晏所涉部分發回高院更審，高院更一審今天宣判。
                台灣高等法院審理「W飯店女子命案」，今天做出更一審判決，認為朱家龍等人轉讓藥品與女子死亡無相當因果關係，依藥事法轉讓偽藥或禁藥罪，改判朱2年10月徒刑。


                土豪哥朱家龍（前左）被控「W飯店女模案件」。（中央社／資料照）
                更多
                「土豪哥」朱家龍被控於民國105年12月2日訂房入住W Hotel，邀約友人洪聖晏、蔡逸學舉辦毒品派對，另邀郭姓被害女子等人參加，並提供大批毒軟糖、毒梅片同歡，導致郭女於12月7日因用毒過量身亡。

                朱家龍4月初在高院更一審就W飯店命案庭做無罪答辯，強調對死者死亡結果感到抱歉，他遭押2年多，請求法官讓他交保回家向父母懺悔。他在庭上指出，對自己之前吸毒玩樂感到後悔，也對死者死亡結果感到遺憾及抱歉，已和死者家屬達成和解，法律上他應負的責任不會逃避，但他已遭押2年多，也2年多沒看到父母，希望法官能讓他交保，讓他回家向父母認錯及懺悔，他會記取這次教訓，不會再發生憾事。

                朱家龍律師表示，朱家龍已和郭女家屬達成和解，和解金也已全數匯款賠償完畢，但並未透露金額。

                蔡逸學及洪聖晏也做無罪答辯；洪聖晏表示，已與死者家屬和解，他會盡力去彌補及贖罪，過兩天就是清明節，之前奶奶過世，他都沒去上香，希望法官讓他具保停押。

                一、二審依藥事法轉讓偽藥致人於死罪判朱家龍10年徒刑；蔡逸學、洪聖晏各被判刑10年、10年6月。最高法院將朱家龍、蔡逸學、洪聖晏所涉部分發回高院更審，高院更一審今天宣判。
            </div>
        </div>

    </div>

</body>
</html>

```

![](/files/-Lf-ImPPiNQ3tpbW0Rci)

### 重點

要知道階層對應關係(繼承與boxmodel與prestyle) 然後才去注意class扛敗

## bootstrap 驗證狀態 ?  加上 jq 驗證寫法

樣式在不同瀏覽器不同效果

Bs有提供一些驗證狀態樣式

form 屬性novalidate不要驗證 ( 表單不驗證 input 屬性 required 必填驗證 ( 但按鈕驗證

### keyword class 驗證產生文字位樣式

valid-feedback invalid-feedback

必須要在js寫驗證判斷才會顯示

其實只是驗證成功失敗時扛拜一個驗證成功或失敗的 class

### Keyword class 驗證欄位樣式

Is-valid Is-invalid

兩種方式 同樣都要用js先驗證判斷值出現後決定要塞class 驗證通過或驗證失敗

然後 feedback 這 可以在文本內安排通過失敗文本 或 安排一個容器 用js改變class 也可以

驗證的js要怎寫? 問google keyword <https://www.google.com/search?rlz=1C1GCEU_zh-TWTW835TW836&q=mail+javascript+regex&spell=1&sa=X&ved=0ahUKEwjbpMTeiJ_iAhXHx4sBHSWJAigQBQgoKAA&biw=1920&bih=936>

正規表達式包覆 /^ 開始 $/ 結束 不是雙引號

Jq 檢測 Test 方法

### 題外話:右鍵檢查可以直接展開那個位置的程式碼

![](/files/-Lf-J9Ckll1NXpfBclGD)

#### ###/RWD/19ValidationStatus.html ( 條測函式前 ( 且鎖住 submit 不讓它 postback

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title></title>

    <link href="Content/bootstrap.min.css" rel="stylesheet" />

    <link href="MyStyle.css" rel="stylesheet" />
</head>
<body>


    <div class="card bg-light">
        <div class="container">

            <form novalidate>
                <div class="form-group">
                    <label for="email">Email:</label>
                    <input id="email" type="email" class="form-control" placeholder="Enter email..." required />
                    <div>
                        
                    </div>
                </div>
                <div class="form-group">
                    <label for="pwd">Password:</label>
                    <input id="pwd" type="password" class="form-control" placeholder="Password" required />
                    <div>
                        
                    </div>
                </div>
                <div class="form-group form-check">
                    <input id="remember" type="checkbox" class="form-check-input" required />
                    <label for="remember">我同意</label>
                    <div>
                       
                    </div>
                </div>
              
                <input id="Button1" type="button" value="submit" class="btn btn-primary" />
            </form>
        </div>
    </div>
    <script src="Scripts/jquery-3.0.0.min.js"></script>

    <script>
        $('#Button1').click(function () {
            if ($('#email').val() == "") {
                $('#email').addClass('is-invalid');
                $('#email+div').addClass('invalid-feedback').text('Required!!');
            }
            else {
                $('#email').removeClass('is-invalid').addClass('is-valid');
                $('#email+div').removeClass().text('');
            }

            var rex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

            if (!rex.test($('#email').val())) {
                $('#email').addClass('is-invalid');
                $('#email+div').addClass('invalid-feedback').text('Please Check Email Format!!');
            }
            else {
                $('#email').removeClass('is-invalid').addClass('is-valid');
                $('#email+div').removeClass().text('');
            }

            if ($('#pwd').val() == "") {
                $('#pwd').addClass('is-invalid');
                $('#pwd+div').addClass('invalid-feedback').text('Required!!');
            }
            else {
                $('#pwd').removeClass('is-invalid').addClass('is-valid');
                $('#pwd+div').removeClass().text('');
            }

            if (!$('#remember').is(':checked')) {
                $('#remember').addClass('is-invalid');
                $('#remember+label+div').addClass('invalid-feedback').text('Please Check it!!');
            }
            else {
                $('#remember').removeClass('is-invalid').addClass('is-valid');
                $('#remember+label+div').removeClass().text('');
            }
        });

        

    </script>
</body>
</html>

```

### ##接著調整架構 (內聚力高耦合力低)&#xD;

一樣的地方放在 function 不一樣的地方當作參數傳入 function

接著寫 click 觸發後&#x20;

驗證過

呼叫 function

if

通過就傳通過的參數 沒通過就傳沒通過的參數

然後驗證呼叫的這件事情也可以調整架構

但只能相同驗證方式同一架構

#### ###巢狀 必填驗證先驗證後 如果有填才進行別的驗證 避免 字被蓋掉&#xD;

### ##JQ 內DOM選擇器 &#xD;

&#x20;+: 下一個兄弟結點NODE  \~:下N個兄弟結點NODE

\#接著處理submit postback問題

下旗標 ? ( 用來輔助驗證通過或失敗的變數

將form取id

使用submit方法

然後弄個旗標值做true或false判斷

### ##最後 改成 keyboard 事件 只要有打字就觸發格式驗證&#xD;

但是必填還是要由click觸發

#### ##預設submit是會送true &#xD;

在這邊我們用 submit(function () 接手 再去判斷 true or false

純html狀態消失才算送出去

但webform會保留狀態就不能這樣判斷

#### ###RWD/19ValidationStatus.html&#xD;

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title></title>

    <link href="Content/bootstrap.min.css" rel="stylesheet" />

    <link href="MyStyle.css" rel="stylesheet" />
</head>
<body>


    <div class="card bg-light">
        <div class="container">

            <form novalidate id="login">
                <div class="form-group">
                    <label for="email">Email:</label>
                    <input id="email" type="email" class="form-control" placeholder="Enter email..." required />
                    <div>
                        
                    </div>
                </div>
                <div class="form-group">
                    <label for="pwd">Password:</label>
                    <input id="pwd" type="password" class="form-control" placeholder="Password" required />
                    <div>
                        
                    </div>
                </div>
                <div class="form-group form-check">
                    <input id="remember" type="checkbox" class="form-check-input" required />
                    <label for="remember">我同意</label>
                    <div>
                       
                    </div>
                </div>
              
                <input id="Button1" type="submit" value="submit" class="btn btn-primary" />
            </form>
        </div>
    </div>
    <script src="Scripts/jquery-3.0.0.min.js"></script>

    <script>
        var flag2 = false;
        var flag = false;
        var rex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

        function StateChange(state,objID,text) {
            if (state) {
                $(objID).removeClass('is-invalid').addClass('is-valid');
                $(objID + '~div').removeClass().text('');              
            }
            else {
                $(objID).removeClass('is-valid').addClass('is-invalid');
                $(objID + '~div').addClass('invalid-feedback').text(text);
            }
            flag = state;
        }

       

        $('#login').submit(function () {
            if (flag2) {
                if ($('#email').val() == "") {
                    StateChange(false, "#email", "Required!!");
                }
                else {
                    StateChange(true, "#email", "");
                }

                if ($('#pwd').val() == "") {
                    StateChange(false, "#pwd", "Required!!");
                }
                else {
                    StateChange(true, "#pwd", "");
                }
                if (!$('#remember').is(':checked')) {
                    StateChange(false, "#remember", "Please Check it!!")
                    flag = false;
                }
                else {
                    StateChange(true, "#remember", "")
                    flag = true;

                }
            }
            console.log(flag);
            console.log(flag2);

            if (flag && flag2 )
                return true;
          

            return false;


        });

        $('#email').keyup(function () {

            if (!rex.test($('#email').val())) {
                StateChange(false, "#email", "Please Check Email Format!!!!");
                flag2 = false;
            }
            else {
                StateChange(true, "#email", "");
                flag2 = true;
            }
        })
        
        
            
        $('#pwd').keyup(function () {
            if ($('#pwd').val().length < 8) {
                StateChange(false, "#pwd", ">8!!");
                flag2 = false;
            }
            else {
                StateChange(true, "#pwd", "");
                flag2 = true;
            }
        })


        //$('#Button1').click(function () {
            
        //});

        

    </script>
</body>
</html>

```

![](/files/-Lf-K_jI3Ui3PW1Tq3fh)

## MVC\_ CRUD 接續昨天

昨天做完查詢(要自己改成輸入)跟刪除

### &#xD;新增

因為index是範本產出裡面已經有create連結

所以我們直接用controll新增get create 的actionresult用來 return View()

第二個用來post的create 表單mether是post就會呼叫這個action

先用簡單繫結法把所有欄位當作參數傳入，必須要跟表單上的name一樣

圖片”檔案”必須要用HttpPostedFileBase型態傳

然後try catch&#x20;

這裡不處理檔名重複問題 ( 實務上要判別

System.IO.Path.GetExtension(fImg.FileName) 可以從主檔名內抓副檔名

寫判斷如果抓到的東西

利用fImg.ContentLength 檔案大小 大於 0

fImg.SaveAs(Server.MapPath(“\~/images/“+fImg.FileName)將檔案轉移到伺服器 ???

將參數轉至變數物件( 包含檔名等等

存檔至資料庫&#x20;

以上為簡單繫結的方式 也可以用複雜繫結

寫好功能後利用這個action右鍵新增檢視使用範本

添加 form的&#x20;

method post&#x20;

action 用 @Url.Action(“Creat”)

enctype=”multipart/form-data”表單類型改為這種 要傳檔案的

產生token

action檢查token

HttpPost底下要加上

範本只需要動

上傳圖片那裏(因為範本的是只要傳圖片檔名(但我們是要檔案

改為input id="fImg" name="fImg" type="file"

底下submit底下把try catch的

@ViewBag.Error補上

#### ###06CRUD/Controllers/HomeController.cs&#xD;

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//00-1-6 using _06CRUD.Models;
using _06CRUD.Models;

namespace _06CRUD.Controllers
{
    public class HomeController : Controller
    {
        //00-1-7 使用Entity建立DB物件
        dbProductEntities db = new dbProductEntities();
        // GET: Home
        //00-2-1 在HomeController裡撰寫Index的Action
        public ActionResult Index()
        {
            return View(db.tProduct.ToList());
        }

        //00-5-1 在HomeController裡撰寫GET及POST的Create Action
        public ActionResult Delete(string id)
        {
            var products = db.tProduct.Where(m => m.fId == id).FirstOrDefault();
            string fileName = products.fImg;
            System.IO.File.Delete(Server.MapPath("~/images/"+fileName));
            db.tProduct.Remove(products);
            db.SaveChanges();

            return RedirectToAction("Index");
        }



        public ActionResult Create()
        {

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(string fId, string fName, decimal fPrice, HttpPostedFileBase fImg)
        {
            try
            {
                //處理商品圖片檔
                string subname = System.IO.Path.GetExtension(fImg.FileName);
                if (subname == ".jpg" || subname==".png")
                {
                    if(fImg.ContentLength>0)
                    {
                        fImg.SaveAs(Server.MapPath("~/images/"+ fImg.FileName));
                    }
                }

                tProduct product = new tProduct();
                product.fId = fId;
                product.fName = fName;
                product.fPrice = fPrice;
                product.fImg = fImg.FileName;

                db.tProduct.Add(product);
                db.SaveChanges();

                return RedirectToAction("Index");

            }
            catch(Exception ex)
            {
                ViewBag.Error = ex.Message;
            }

            return View();
        }


    }
}




```

#### ###06CRUD/Views/Home/Create.cshtml

```
@model _06CRUD.Models.tProduct

@{
    ViewBag.Title = "新增產品";
}

<h2>新增產品</h2>

@*@using (Html.BeginForm()) 
{*@
<form method="post" action="@Url.Action("Create")" enctype="multipart/form-data">
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @*<h4>tProduct</h4>*@
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.fId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fId, "", 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.fPrice, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fPrice, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fPrice, "", new { @class = "text-danger" })
            </div>
        </div>

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

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
                @ViewBag.Error
            </div>
        </div>
    </div>
    @*}*@
</form>
<div>
    @Html.ActionLink("返回列表", "Index")
</div>
```

![](/files/-Lf-Kze-b_m0CBKOx4fe)

#### ###老師步驟

```
//00-1 利用Entity Framework建立Model(DB First)
//00-1-1 建立dbProduct.mdb資料庫Model
//       在Models上按右鍵,選擇加入,新增項目,資料,ADO.NET實體資料模型,名稱輸入"ProductModel",按新增
//       來自資料庫的EF Designer
//       連接dbProduct.mdf資料庫,連線名稱不修改,按下一步按鈕
//       選擇Entity Framework 6.x, 按下一步按鈕
//       資料表勾選"tProuct", 按完成鈕
//       若跳出詢問方法按確定鈕
//00-1-2 在專案上按右鍵,建置
//00-1-3 在tProduct.cs裡加入欄位名稱顯示(需using System.ComponentModel)
//00-1-4 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//00-1-5 指定控制器名稱為HomeController,並開啟HomeController
//00-1-6 using _00MVC.Models
//00-1-7 使用Entity建立DB物件


//00-2 製作Index頁面的顯示所有產品功能
//00-2-1 在HomeController裡撰寫Index的Action
//00-2-2 在public ActionResult Index()上按右鍵,新增檢視,建立Index View
//00-2-3 進行下列設定:
//       View name:Index
//       Template:List
//       Model class:tStudent(_00MVC.Models)
//       Data context class:dbProductEntities(_00MVC.Models)
//       勾選Use a layout pages
//       按下Add
//00-2-5 修改Index View,英文文字為中文
//00-2-6 修改圖片顯示處

//00-3 製作刪除功能
//00-3-1 在HomeController裡撰寫Delete的Action

//00-4 製作Create頁面及新增產品功能
//00-4-1 在HomeController裡撰寫GET及POST的Create Action
//00-4-2 在public ActionResult Create()上按右鍵,新增檢視,建立Create View
//00-4-3 進行下列設定:
//       View name:Create
//       Template:Create
//       Model class:tStudent(_00MVC.Models)
//       Data context class:dbProductEntities(_00MVC.Models)
//       勾選Use a layout pages
//       按下Add
//00-4-4 修改Index View,英文文字為中文
//00-4-5 修改form的HTML Helper為一般的from
//00-4-6 修改圖片上傳處表單
//00-4-7 加入例外訊息顯示處

```

Debug ie 問題 抓 filename抓出來的值不一樣 以上從改 (資安問題

D:\AAA\img.jpg IE

img.jpg  chrome

要利用GetFileName方法

順道調整架構 整理成以下

### #接著換修改&#xD;

Action 沒有順序性先寫哪種沒關係

首先新增一個 Edit 的 action 然後

用get接參數 ( 簡單繫結即可

接著將參數用lamaba查詢到的資料 return丟回View

接著新增一個 post 一樣token

圖必須要看 (沒有就沒事

有沒有置換有的話就要刪除原來的圖然後上傳新檔案

還要傳圖片目前的檔名才能夠去判斷是新還舊

接著 如果有置換

就刪除 system.io.file.delete(server.mappath(\~\~\~\~)

然後將舊檔名改為新檔名

存檔

如果沒改則把新檔名改為舊檔名做存檔

#### ### 06CRUD/Controllers/HomeController.cs&#xD;

```
@model _06CRUD.Models.tProduct

@{
    ViewBag.Title = "新增產品";
}

<h2>新增產品</h2>

@*@using (Html.BeginForm()) 
{*@
<form method="post" action="@Url.Action("Create")" enctype="multipart/form-data">
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @*<h4>tProduct</h4>*@
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.fId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fId, "", 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.fPrice, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fPrice, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fPrice, "", new { @class = "text-danger" })
            </div>
        </div>

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

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
                @ViewBag.Error
            </div>
        </div>
    </div>
    @*}*@
</form>
<div>
    @Html.ActionLink("返回列表", "Index")
</div>
```

接著新增一個edit的view一樣預設範本 但是把 form 手動編輯

然後圖片那裡用隱藏按鈕用於簡單繫結傳送舊檔名資料

預設的範本 pk不能改 應為改了 你整個動態網頁的東西都會有機會出錯

然後範本很多東西都重複產生可能都要註解 ( 熟悉才能註解不然會出錯

剛剛錯誤是 寫入資料庫時pk重複

新增是增加的

修改是修改重複的

物件一定要有傳過來做查詢顯示用

但是不能新增add

要直接save

以下為改過的 control

#### ### /06CRUD/Controllers/HomeController.cs&#xD;

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//00-1-6 using _06CRUD.Models;
using _06CRUD.Models;

namespace _06CRUD.Controllers
{
    public class HomeController : Controller
    {
        //00-1-7 使用Entity建立DB物件
        dbProductEntities db = new dbProductEntities();
        // GET: Home
        //00-2-1 在HomeController裡撰寫Index的Action
        public ActionResult Index()
        {
            return View(db.tProduct.ToList());
        }

        //00-5-1 在HomeController裡撰寫GET及POST的Create Action
        public ActionResult Delete(string id)
        {
            var products = db.tProduct.Where(m => m.fId == id).FirstOrDefault();
            string fileName = products.fImg;
            System.IO.File.Delete(Server.MapPath("~/images/"+fileName));
            db.tProduct.Remove(products);
            db.SaveChanges();

            return RedirectToAction("Index");
        }


        //00-5-1 在HomeController裡撰寫GET及POST的Edit Action
        public ActionResult Create()
        {

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(string fId, string fName, decimal fPrice, HttpPostedFileBase fImg)
        {
            try
            {
                //處理商品圖片檔
                string fileName = "";
                string subname = System.IO.Path.GetExtension(fImg.FileName);
                if (subname == ".jpg" || subname==".png")
                {
                    if(fImg.ContentLength>0)
                    {
                        fileName = System.IO.Path.GetFileName(fImg.FileName);
                        fImg.SaveAs(Server.MapPath("~/images/"+ fileName));
                    }
                }

                tProduct product = new tProduct();
                product.fId = fId;
                product.fName = fName;
                product.fPrice = fPrice;
                product.fImg = fileName;

                db.tProduct.Add(product);
                db.SaveChanges();

                return RedirectToAction("Index");

            }
            catch(Exception ex)
            {
                ViewBag.Error = ex.Message;
            }

            return View();
        }


        public ActionResult Edit(string id)
        {

            return View(db.tProduct.Where(m=>m.fId==id).FirstOrDefault());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(string fId, string fName, decimal fPrice, HttpPostedFileBase fImg,string oldImg)
        {
            try
            {
                
                string fileName = "";

                if (fImg != null)
                {
                    //處理商品圖片檔
                    string subname = System.IO.Path.GetExtension(fImg.FileName);
                    if (subname == ".jpg" || subname == ".png")
                    {
                        if (fImg.ContentLength > 0)
                        {
                            System.IO.File.Delete(Server.MapPath("~/images/" + oldImg));

                            fileName = System.IO.Path.GetFileName(fImg.FileName);
                            fImg.SaveAs(Server.MapPath("~/images/" + fileName));
                        }
                    }

                }
                else
                {
                    fileName = oldImg;
                }
                //tProduct product = new tProduct();
                //product.fId = fId;
                var product= db.tProduct.Where(m => m.fId == fId).FirstOrDefault();

                product.fName = fName;
                product.fPrice = fPrice;
                product.fImg = fileName;

                //db.tProduct.Add(product);
                db.SaveChanges();

                return RedirectToAction("Index");

            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
            }

            return View();
        }

    }
}

```

最後會貼一次 完整的 CRUD所有的程式碼與大概網站結構圖

#### ###06CRUD/App\_Data/dbProduct.mdf

![](/files/-Lf-Kze0BjJyna26iw6h)

#### ### /06CRUD/Models/tProduct.cs

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

namespace _06CRUD.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    
    public partial class tProduct
    {
        [DisplayName("產品編號")]
        public string fId { get; set; }
        [DisplayName("品名")]
        public string fName { get; set; }
        [DisplayName("單價")]
        public Nullable<decimal> fPrice { get; set; }
        [DisplayName("圖示")]
        public string fImg { get; set; }
    }
}

```

#### ###06CRUD/Controllers/HomeController.cs

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//00-1-6 using _06CRUD.Models;
using _06CRUD.Models;

namespace _06CRUD.Controllers
{
    public class HomeController : Controller
    {
        //00-1-7 使用Entity建立DB物件
        dbProductEntities db = new dbProductEntities();
        // GET: Home
        //00-2-1 在HomeController裡撰寫Index的Action
        public ActionResult Index()
        {
            return View(db.tProduct.ToList());
        }

        //00-5-1 在HomeController裡撰寫GET及POST的Create Action
        public ActionResult Delete(string id)
        {
            var products = db.tProduct.Where(m => m.fId == id).FirstOrDefault();
            string fileName = products.fImg;
            System.IO.File.Delete(Server.MapPath("~/images/"+fileName));
            db.tProduct.Remove(products);
            db.SaveChanges();

            return RedirectToAction("Index");
        }


        //00-5-1 在HomeController裡撰寫GET及POST的Edit Action
        public ActionResult Create()
        {

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(string fId, string fName, decimal fPrice, HttpPostedFileBase fImg)
        {
            try
            {
                //處理商品圖片檔
                string fileName = "";
                string subname = System.IO.Path.GetExtension(fImg.FileName);
                if (subname == ".jpg" || subname==".png")
                {
                    if(fImg.ContentLength>0)
                    {
                        fileName = System.IO.Path.GetFileName(fImg.FileName);
                        fImg.SaveAs(Server.MapPath("~/images/"+ fileName));
                    }
                }

                tProduct product = new tProduct();
                product.fId = fId;
                product.fName = fName;
                product.fPrice = fPrice;
                product.fImg = fileName;

                db.tProduct.Add(product);
                db.SaveChanges();

                return RedirectToAction("Index");

            }
            catch(Exception ex)
            {
                ViewBag.Error = ex.Message;
            }

            return View();
        }


        public ActionResult Edit(string id)
        {

            return View(db.tProduct.Where(m=>m.fId==id).FirstOrDefault());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(string fId, string fName, decimal fPrice, HttpPostedFileBase fImg,string oldImg)
        {
            try
            {
                
                string fileName = "";

                if (fImg != null)
                {
                    //處理商品圖片檔
                    string subname = System.IO.Path.GetExtension(fImg.FileName);
                    if (subname == ".jpg" || subname == ".png")
                    {
                        if (fImg.ContentLength > 0)
                        {
                            System.IO.File.Delete(Server.MapPath("~/images/" + oldImg));

                            fileName = System.IO.Path.GetFileName(fImg.FileName);
                            fImg.SaveAs(Server.MapPath("~/images/" + fileName));
                        }
                    }

                }
                else
                {
                    fileName = oldImg;
                }
                //tProduct product = new tProduct();
                //product.fId = fId;
                var product= db.tProduct.Where(m => m.fId == fId).FirstOrDefault();

                product.fName = fName;
                product.fPrice = fPrice;
                product.fImg = fileName;

                //db.tProduct.Add(product);
                db.SaveChanges();

                return RedirectToAction("Index");

            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
            }

            return View();
        }

    }
}

```

#### ###06CRUD/Views/Shared/\_Layout.cshtml

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                </ul>
            </div>
        </div>
    </div>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
</body>
</html>

```

#### ###06CRUD/Views/Home/Index.cshtml

```
@model IEnumerable<_06CRUD.Models.tProduct>
@*//00-2-5 修改Index View,英文文字為中文*@
@{
    ViewBag.Title = "產品列表";
}

<h2>產品列表</h2>

<p>
    @Html.ActionLink("新增商品", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.fName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fPrice)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fImg)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.fName)
            </td>
            <td>

                @Html.DisplayFor(modelItem => item.fPrice)
            </td>
            <td>
                @*//00-2-6 修改圖片顯示處*@
                @*@Html.DisplayFor(modelItem => item.fImg)*@
                <img src="~/images/@item.fImg" width="120" />
            </td>
            <td>
                @Html.ActionLink("修改", "Edit", new { id = item.fId }) |
                @*@Html.ActionLink("Details", "Details", new { id=item.fId }) |*@
                @Html.ActionLink("刪除", "Delete", new { id = item.fId }, new { onclick = "return confirm('確定刪除??')" })
            </td>
        </tr>
    }

</table>

```

#### ###06CRUD/Views/Home/Create.cshtml

```
@model _06CRUD.Models.tProduct
@*//00-4-4 修改Index View,英文文字為中文*@
@{
    ViewBag.Title = "新增產品";
}

<h2>新增產品</h2>

@*//00-4-6 修改圖片上傳處表單*@
@*@using (Html.BeginForm())
    {*@
<form method="post" action="@Url.Action("Create")" enctype="multipart/form-data">
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @*<h4>tProduct</h4>*@
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.fId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fId, "", 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.fPrice, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fPrice, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fPrice, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.fImg, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*@Html.EditorFor(model => model.fImg, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.fImg, "", new { @class = "text-danger" })*@
                @*//00-4-6 修改圖片上傳處表單*@
                <input id="fImg" name="fImg" type="file" class="form-control" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
                @*//00-4-7 加入例外訊息顯示處*@
                @ViewBag.Error
            </div>
        </div>
    </div>
    @*}*@
</form>
<div>
    @Html.ActionLink("返回列表", "Index")
</div>

```

#### ###06CRUD/Views/Home/Edit.cshtml

```
@model _06CRUD.Models.tProduct

@{
    ViewBag.Title = "產品編輯";
}

<h2>產品編輯</h2>

@*@using (Html.BeginForm())
{*@
<form method="post" action="@Url.Action("Edit")" enctype="multipart/form-data">


    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        @*<h4>tProduct</h4>*@
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.fId)
        @*<input id="fId" name="fId" type="hidden" value="@Model.fId" />*@
        <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.fPrice, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fPrice, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fPrice, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.fImg, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*@Html.EditorFor(model => model.fImg, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fImg, "", new { @class = "text-danger" })*@
                <input id="oldImg" name="oldImg" type="hidden" value="@Model.fImg" />
                <img src="~/images/@Model.fImg" width="200" />
                
                <input id="fImg" name="fImg" type="file" class="form-control" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
                @ViewBag.Error
            </div>
        </div>
    </div>
    @*}*@
</form>
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

```

#### ###老師步驟

```
//00-1 利用Entity Framework建立Model(DB First)
//00-1-1 建立dbProduct.mdb資料庫Model
//       在Models上按右鍵,選擇加入,新增項目,資料,ADO.NET實體資料模型,名稱輸入"ProductModel",按新增
//       來自資料庫的EF Designer
//       連接dbProduct.mdf資料庫,連線名稱不修改,按下一步按鈕
//       選擇Entity Framework 6.x, 按下一步按鈕
//       資料表勾選"tProuct", 按完成鈕
//       若跳出詢問方法按確定鈕
//00-1-2 在專案上按右鍵,建置
//00-1-3 在tProduct.cs裡加入欄位名稱顯示(需using System.ComponentModel)
//00-1-4 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//00-1-5 指定控制器名稱為HomeController,並開啟HomeController
//00-1-6 using _00MVC.Models
//00-1-7 使用Entity建立DB物件


//00-2 製作Index頁面的顯示所有產品功能
//00-2-1 在HomeController裡撰寫Index的Action
//00-2-2 在public ActionResult Index()上按右鍵,新增檢視,建立Index View
//00-2-3 進行下列設定:
//       View name:Index
//       Template:List
//       Model class:tStudent(_00MVC.Models)
//       Data context class:dbProductEntities(_00MVC.Models)
//       勾選Use a layout pages
//       按下Add
//00-2-5 修改Index View,英文文字為中文
//00-2-6 修改圖片顯示處

//00-3 製作刪除功能
//00-3-1 在HomeController裡撰寫Delete的Action

//00-4 製作Create頁面及新增產品功能
//00-4-1 在HomeController裡撰寫GET及POST的Create Action
//00-4-2 在public ActionResult Create()上按右鍵,新增檢視,建立Create View
//00-4-3 進行下列設定:
//       View name:Create
//       Template:Create
//       Model class:tStudent(_00MVC.Models)
//       Data context class:dbProductEntities(_00MVC.Models)
//       勾選Use a layout pages
//       按下Add
//00-4-4 修改Index View,英文文字為中文
//00-4-5 修改form的HTML Helper為一般的from
//00-4-6 修改圖片上傳處表單
//00-4-7 加入例外訊息顯示處

```

## #六月份會從頭做到尾一次給我們看


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://johch3n611u.gitbook.io/c50108/ju-li-cheng-bei/201905/2019-0516.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
