2019/0528/Bootstrap Components 元件介紹 + MVC 登入驗證 + 商品加入購物車 實作

Bootstrap Components

Bootstrap dropdown上次套件庫bug

Keyword Disable Active

不止擺選單,只要不是超鏈結

button與dropdown合併做法

###\WebApplication\responsive_web_design\RWD\24Dropdown.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>
    <div class="container">
        <!--基本型-->
        <div class="dropdown">
            <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown" id="ddMenu1">
                Menu

            </button>
            <div class="dropdown-menu" aria-labelledby="ddMenu1">
                <a href="#" class="dropdown-item">Action</a>
                <a href="#" class="dropdown-item disabled">Another action</a>
                <a href="#" class="dropdown-item">Something else here</a>
                <a href="#" class="dropdown-item active">Separated link</a>
                <div class="dropdown-divider"></div>
                <a href="#" class="dropdown-item">Action</a>
                <a href="#" class="dropdown-item">Another action</a>

            </div>
        </div>
        <hr />
        <!--群組按鈕-->
        <div class="btn-group">
            <button class="btn btn-danger" data-toggle="dropdown" id="ddMenu2">
                Menu
            </button>
            <button class="btn btn-danger dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" id="ddMenu2"></button>
            <div class="dropdown-menu" aria-labelledby="ddMenu2">
                <a href="#" class="dropdown-item">Action</a>
                <a href="#" class="dropdown-item">Another action</a>
                <a href="#" class="dropdown-item">Something else here</a>
                <a href="#" class="dropdown-item">Separated link</a>
                <div class="dropdown-divider"></div>
                <a href="#" class="dropdown-item">Action</a>
                <a href="#" class="dropdown-item">Another action</a>

            </div>
        </div>


        <hr />
        <br />
        <br /><br /><br /><br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <!--選單往上出現-->
        <div class="btn-group dropup">
            <button class="btn btn-danger" data-toggle="dropdown" id="ddMenu3">
                Menu
            </button>
            <button class="btn btn-danger dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" id="ddMenu3" aria-haspopup="true"></button>
            <div class="dropdown-menu" aria-labelledby="ddMenu3">
                <a href="#" class="dropdown-item">Action</a>
                <a href="#" class="dropdown-item">Another action</a>
                <a href="#" class="dropdown-item">Something else here</a>
                <a href="#" class="dropdown-item">Separated link</a>
                <div class="dropdown-divider"></div>
                <a href="#" class="dropdown-item">Action</a>
                <a href="#" class="dropdown-item">Another action</a>

            </div>
        </div>
        <hr />
        <!--選單往左側出現-->
        <div class="btn-group dropleft">
            <button class="btn btn-danger dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" id="ddMenu4"></button>
            <button class="btn btn-danger" data-toggle="dropdown" id="ddMenu4">
                Menu
            </button>

            <div class="dropdown-menu" aria-labelledby="ddMenu4">
                <a href="#" class="dropdown-item">Action</a>
                <a href="#" class="dropdown-item">Another action</a>
                <a href="#" class="dropdown-item">Something else here</a>
                <a href="#" class="dropdown-item">Separated link</a>
                <div class="dropdown-divider"></div>
                <a href="#" class="dropdown-item">Action</a>
                <a href="#" class="dropdown-item">Another action</a>

            </div>
        </div>
        <hr />
        <!--Responsive選單的對齊-->
        <div class="dropdown" style="border:1px solid">
            <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown" data-display="static">
                如果大螢幕的時候選單往右靠,一般大小螢幕時用預設方式對齊

            </button>
            <div class="dropdown-menu dropdown-menu-lg-right">
                <a href="#" class="dropdown-item">Action</a>
                <a href="#" class="dropdown-item disabled">Another action</a>
                <a href="#" class="dropdown-item">Something else here</a>
                <a href="#" class="dropdown-item active">Separated link</a>
                <div class="dropdown-divider"></div>
                <a href="#" class="dropdown-item">Action</a>
                <a href="#" class="dropdown-item">Another action</a>

            </div>
        </div>

        <hr />
        <!--純文字-->
        <div class="dropdown">
            <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
                Text

            </button>
            <div class="dropdown-menu p-4 text-danger" style="max-width:250px">
                <p>
                    asdfdasfdasfasdfdasfdas
                </p>
                <p class="mb-0">
                    444444444
                </p>
            </div>
        </div>

        <hr />

        <!--與Form合併使用-->
        <div class="dropdown">
            <button class="btn btn-primary" data-toggle="dropdown">
                登入系統

            </button>
            <div class="dropdown-menu">
                <form class="px-4 py-3">
                    <div class="form-group">
                        <label for="email">Email:</label>
                        <input id="email" type="email" class="form-control" placeholder="Enter email..." required />
                    </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="Sign in" class="btn btn-secondary" />
                </form>
                <div class="dropdown-divider"></div>
                <a href="#" class="dropdown-item">註冊會員</a>
                <a href="#" class="dropdown-item">忘記密碼</a>
            </div>
        </div>
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />  <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />


        <hr />
        <!--與Button合併使用-->
        <div class="btn-group">
            <button type="button" class="btn btn-info">Item 1</button>
            <button type="button" class="btn btn-info">Item 2</button>
            <div class="btn-group">
                <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">Item 3</button>
                <div class="dropdown-menu">
                    <a href="#" class="dropdown-item">Action</a>
                    <a href="#" class="dropdown-item">Another action</a>
                    <a href="#" class="dropdown-item">Something else here</a>
                    <a href="#" class="dropdown-item">Separated link</a>
                    <div class="dropdown-divider"></div>
                    <a href="#" class="dropdown-item">Action</a>
                    <a href="#" class="dropdown-item">Another action</a>

                </div>
            </div>
            <button type="button" class="btn btn-info">Item 4</button>
        </div>

        <br />
        <br />
        <br />
        <br />
        <br />
        <br />  <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />

    </div>


    <script src="Scripts/jquery-3.0.0.min.js"></script>
    <script src="Scripts/bootstrap.bundle.min.js"></script>
    <!--<script src="Scripts/popper.js"></script>-->
    <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="Scripts/bootstrap.min.js"></script>-->


    <!--<script src="Scripts/bootstrap.bundle.min.js"></script>-->
    <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>-->
    <!--<script src="Scripts/popper.js"></script>-->
    <!--<script src="Scripts/bootstrap.min.js"></script>-->




</body>
</html>

導覽

Keyword

Nav

Nav-item

Nav-tabs

Nav-pills

Flex

justify

應用jq

data-toggle

###:\Little-donkey\WebApplication\responsive_web_design\RWD\25Navs.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>
    <div class="container">
        <ul class="nav justify-content-center">
            <li class="nav-item"><a href="#" class="nav-link">Item 1</a></li>
            <li class="nav-item"><a href="#" class="nav-link active">Item 2</a></li>
            <li class="nav-item"><a href="#" class="nav-link">Item 3</a></li>
            <li class="nav-item"><a href="#" class="nav-link disabled">Item 4</a></li>
        </ul>
        <hr />
        <ul class="nav flex-column">
            <li class="nav-item"><a href="#" class="nav-link">Item 1</a></li>
            <li class="nav-item"><a href="#" class="nav-link active">Item 2</a></li>
            <li class="nav-item"><a href="#" class="nav-link">Item 3</a></li>
            <li class="nav-item"><a href="#" class="nav-link disabled">Item 4</a></li>
        </ul>
        <hr />
        <ul class="nav nav-tabs nav-fill">
            <li class="nav-item"><a href="#" class="nav-link">Item 1</a></li>
            <li class="nav-item"><a href="#" class="nav-link active">Item 2</a></li>
            <li class="nav-item"><a href="#" class="nav-link">Item 3</a></li>
            <li class="nav-item"><a href="#" class="nav-link disabled">Item 4</a></li>
        </ul>
        <hr />
        <ul class="nav nav-pills">
            <li class="nav-item"><a href="#" class="nav-link">Item 1</a></li>
            <li class="nav-item"><a href="#" class="nav-link active">Item 2</a></li>
            <li class="nav-item"><a href="#" class="nav-link">Item 3</a></li>
            <li class="nav-item"><a href="#" class="nav-link disabled">Item 4</a></li>
        </ul>
        <hr />
        <hr />
        <ul class="nav nav-tabs nav-fill">
            <li class="nav-item"><a href="#item1" class="nav-link active" data-toggle="tab">Item 1</a></li>
            <li class="nav-item"><a href="#item2" class="nav-link" data-toggle="tab">Item 2</a></li>
            <li class="nav-item"><a href="#item3" class="nav-link" data-toggle="tab">Item 3</a></li>
            <li class="nav-item"><a href="#item4" class="nav-link disabled" data-toggle="tab">Item 4</a></li>
        </ul>
        <div class="tab-content">
            <div class="tab-pane active fade show" id="item1">
                <h2>Item 1</h2>
                <p>
                    mbitioni dedisse scripsisse iudicaretur. Cras mattis iudicium purus sit amet fermentum. Donec sed odio operae, eu vulputate felis rhoncus. Praeterea iter est quasdam res quas ex communi. At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius Galliae in diem certam indicere. Cras mattis iudicium purus sit amet fermentum.
                </p>
            </div>
            <div class="tab-pane fade" id="item2">
                <h2>Item 2</h2>
                <p>
                    mbitioni dedisse scripsisse iudicaretur. Cras mattis iudicium purus sit amet fermentum. Donec sed odio operae, eu vulputate felis rhoncus. Praeterea iter est quasdam res quas ex communi. At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius Galliae in diem certam indicere. Cras mattis iudicium purus sit amet fermentum.
                </p>
            </div>
            <div class="tab-pane fade" id="item3">
                <h2>Item 3</h2>
                <p>
                    mbitioni dedisse scripsisse iudicaretur. Cras mattis iudicium purus sit amet fermentum. Donec sed odio operae, eu vulputate felis rhoncus. Praeterea iter est quasdam res quas ex communi. At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius Galliae in diem certam indicere. Cras mattis iudicium purus sit amet fermentum.
                </p>
            </div>

        </div>

        <hr />
        <hr />
        <div class="row">
            <div class="col-sm-3">
                <ul class="nav nav-pills flex-column">
                    <li class="nav-item"><a href="#item11" class="nav-link active" data-toggle="pill">Item 1</a></li>
                    <li class="nav-item"><a href="#item22" class="nav-link" data-toggle="pill">Item 2</a></li>
                    <li class="nav-item"><a href="#item33" class="nav-link" data-toggle="pill">Item 3</a></li>
                    <li class="nav-item"><a href="#item44" class="nav-link disabled" data-toggle="pill">Item 4</a></li>
                </ul>
            </div>
            <div class="col-sm-9">
                <div class="tab-content">
                    <div class="tab-pane active fade show" id="item11">
                        <h2>Item 1</h2>
                        <p>
                            mbitioni dedisse scripsisse iudicaretur. Cras mattis iudicium purus sit amet fermentum. Donec sed odio operae, eu vulputate felis rhoncus. Praeterea iter est quasdam res quas ex communi. At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius Galliae in diem certam indicere. Cras mattis iudicium purus sit amet fermentum.
                        </p>
                    </div>
                    <div class="tab-pane fade" id="item22">
                        <h2>Item 2</h2>
                        <p>
                            mbitioni dedisse scripsisse iudicaretur. Cras mattis iudicium purus sit amet fermentum. Donec sed odio operae, eu vulputate felis rhoncus. Praeterea iter est quasdam res quas ex communi. At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius Galliae in diem certam indicere. Cras mattis iudicium purus sit amet fermentum.
                        </p>
                    </div>
                    <div class="tab-pane fade" id="item33">
                        <h2>Item 3</h2>
                        <p>
                            mbitioni dedisse scripsisse iudicaretur. Cras mattis iudicium purus sit amet fermentum. Donec sed odio operae, eu vulputate felis rhoncus. Praeterea iter est quasdam res quas ex communi. At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius Galliae in diem certam indicere. Cras mattis iudicium purus sit amet fermentum.
                        </p>
                    </div>
                </div>
                </div>
            </div>
        </div>


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

#pagination 分頁 樣式

Html5 nav 導覽列 SEO 語意化

調一般的置中 輔助類別 ( justify-content-center …

### \WebApplication\responsive_web_design\RWD\26Pagination.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>
    <div class="container">
        <div class="nav">
            <ul class="pagination">
                <li class="page-item"><a class="page-link" href="#">Previous</a></li>
                <li class="page-item"><a class="page-link" href="#">1</a></li>
                <li class="page-item"><a class="page-link" href="#">2</a></li>
                <li class="page-item"><a class="page-link" href="#">3</a></li>
                <li class="page-item"><a class="page-link" href="#">Next</a></li>
            </ul>
        </div>


        <nav class="nav">
            <ul class="pagination">
                <li class="page-item">
                    <a class="page-link" href="#">
                        &laquo;
                    </a>
                </li>
                <li class="page-item"><a class="page-link" href="#">1</a></li>
                <li class="page-item"><a class="page-link" href="#">2</a></li>
                <li class="page-item"><a class="page-link" href="#">3</a></li>
                <li class="page-item"><a class="page-link" href="#"> &raquo;</a></li>
            </ul>
        </nav>

        <nav class="nav justify-content-center">
            <ul class="pagination">
                <li class="page-item">
                    <a class="page-link" href="#">
                        &laquo;
                    </a>
                </li>
                <li class="page-item"><a class="page-link" href="#">1</a></li>
                <li class="page-item"><a class="page-link" href="#">2</a></li>
                <li class="page-item"><a class="page-link" href="#">3</a></li>
                <li class="page-item"><a class="page-link" href="#"> &raquo;</a></li>
            </ul>
        </nav>
    </div>
 <script src="Scripts/jquery-3.0.0.min.js"></script>
    <script src="Scripts/bootstrap.bundle.min.js"></script>
</body>
</html>

#題外話 分頁功能

MVC 分頁較麻煩像是進階的購物車 ( 1.JQ 2.NUGET套件

Webform分頁簡單 ( 因為狀態會保留住

#27GridView_Pagination.aspx

示範 webform與gridview套bootstrap 用cssdom 與 jqdom 塞 class屬性

###\WebApplication\responsive_web_design\RWD\27GridView_Pagination.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="27GridView_Pagination.aspx.cs" Inherits="_27GridView_Pagination" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <style>
       #GridView1 > tbody > tr:first-child{
           background-color:#ce0059;
           color:white;
       }
         #GridView1 > tbody > tr:last-child{
           background-color:#ffffff;
           color:cadetblue;
       }
       .PageActive{
           background-color:#ce0059;
            color:white;
       }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div class="container">

            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MySystemConnectionString %>" SelectCommand="SELECT * FROM [Products2]"></asp:SqlDataSource>
            <asp:GridView CssClass="table table-danger" ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="Product_ID" DataSourceID="SqlDataSource1" PageSize="1">
                <Columns>
                    <asp:BoundField DataField="Product_ID" HeaderText="Product_ID" ReadOnly="True" SortExpression="Product_ID" />
                    <asp:BoundField DataField="Product_Name" HeaderText="Product_Name" SortExpression="Product_Name" />
                    <asp:BoundField DataField="Product_Img" HeaderText="Product_Img" SortExpression="Product_Img" />
                    <asp:BoundField DataField="Product_Price" HeaderText="Product_Price" SortExpression="Product_Price" />
                    <asp:BoundField DataField="Product_price2" HeaderText="Product_price2" SortExpression="Product_price2" />
                    <asp:BoundField DataField="Product_Intro" HeaderText="Product_Intro" SortExpression="Product_Intro" />
                    <asp:CheckBoxField DataField="Product_Status" HeaderText="Product_Status" SortExpression="Product_Status" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
    <script src="Scripts/jquery-3.0.0.min.js"></script>

    <script src="Scripts/bootstrap.bundle.min.js"></script>
    <script>
        $('#GridView1 > tbody > tr:last-child>td>table').addClass('nav justify-content-center');

        $('#GridView1 > tbody > tr:last-child>td>table td').addClass('page-item');
        $('#GridView1 > tbody > tr:last-child>td>table td>a').addClass('page-link');
         $('#GridView1 > tbody > tr:last-child>td>table td>span').addClass('page-link PageActive');
    </script>

</body>
</html>

#28Progress.html 進度欄 ( 樣式

Keyword

Progress-bar

Progress-bar-striped

progress-bar-animated

但長度就要利用css style 表達

很多keyword … 很多樣式動畫

###WebApplication\responsive_web_design\RWD\ 28Progress.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>
    <div class="container">
        <div class="progress">
            <div class="progress-bar" style="width:25%"></div>
        </div>
        <hr />
        <div class="progress">
            <div class="progress-bar" style="width:45%">45%</div>
        </div>
        <hr />
        <div class="progress">
            <div class="progress-bar bg-success" style="width:45%">45%</div>
        </div>
        <hr />
        <div class="progress">
            <div class="progress-bar bg-warning" style="width:45%">45%</div>
        </div>

        <hr />
        <div class="progress">
            <div class="progress-bar bg-danger" style="width:40%">40%</div>
            <div class="progress-bar bg-warning" style="width:35%">35%</div>
            <div class="progress-bar bg-success" style="width:25%">25%</div>
        </div>
        <hr />
        <div class="progress">
            <div class="progress-bar bg-success progress-bar-striped" style="width:45%">45%</div>
        </div>
        <hr />
        <div class="progress">
            <div class="progress-bar bg-warning progress-bar-striped" style="width:45%">45%</div>
        </div>

        <hr />
        <div class="progress" id="myProgress">
            <div class="progress-bar bg-danger progress-bar-striped" style="width:45%">45%</div>
        </div>
        <input id="Button1" type="button" value="button" />


        <hr />
        <div class="progress" id="myProgress2">
            <div class="progress-bar bg-danger progress-bar-striped"></div>
        </div>
        
    </div>


    <script src="Scripts/jquery-3.0.0.min.js"></script>
    <script src="Scripts/bootstrap.bundle.min.js"></script>
    <script>
        $('#Button1').click(function () {
            $('#myProgress>div').addClass('progress-bar-animated')
        });

        var a= 0;
        function timer() {
            a += 2;
            $('#myProgress2>div').text(a + '% Complete');
            $('#myProgress2>div').css({'width':a+'%'});

            if (a < 100)
                setTimeout("timer()",200);
        }
        timer();
    </script>
</body>
</html>

#spinner 讀取中樣式

還在執行 旋轉的樣式 ( 功能都必須寫javascript

Ajax json requses and reghsad time

Keyword

spinner-border

text-danger/warning

spinner-grow

### WebApplication\responsive_web_design\RWD\29Spinner.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>
    <div class="container">

        <div class="spinner-border">

        </div>

        <div class="spinner-border text-danger">

        </div>
        <div class="spinner-border text-warning">

        </div>
        <hr />
        <div class="spinner-grow text-danger">

        </div>
        <div class="spinner-grow text-warning">

        </div>

        <hr />
        <div class="d-flex align-items-center">
            <strong>Loading....</strong>
            <div class="spinner-grow text-danger ml-auto">

            </div>
        </div>


        <hr />
        <button class="btn btn-success btn-lg" id="mybtn">
            
            Submit
        </button>
    </div>


    <script src="Scripts/jquery-3.0.0.min.js"></script>
    <script src="Scripts/bootstrap.bundle.min.js"></script>
   <script>
       $('#mybtn').click(function () {
           $(this).addClass('disabled');
           //$('#mybtn span')

           $(this).html('<span class="spinner-border"></span>Loading....');
           
           setTimeout("test()", 3000);
       });

       
       function test() {
         
           $('#mybtn').text('Submit');
           $('#mybtn').removeClass('disabled');
       }
   </script>
</body>
</html>

#MVC會員登入 加入購物車功能

( 單元劇結束 下一次會講一整個MVC專案 ( 留言板 IG

(資料庫端應用程式端其實都可以寫

ViewModel要去再看一下功能定義

4張表就是4個class

顯示using System.ComponentModel; 驗證using System.ComponentModel.DataAnnotations;

###tOrderDetail.cs

大部分組別 購物車table

但其實可以訂單明細就是購物車只要一個欄位去做判別 是訂單還是購物車

(但大部分都是用在登入後

沒有要做商品管理(上下架(所以不驗證商品表單

整理model

### 08ShoppingCar/Models/tMember.cs

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

namespace _08ShoppingCar.Models
{
    using System;
    using System.Collections.Generic;

    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    
    public partial class tMember
    {
        public int fId { get; set; }
        [DisplayName("帳號")]
        [Required]
        public string fUserId { get; set; }
        [DisplayName("密碼")]
        [Required]
        public string fPwd { get; set; }
        [DisplayName("姓名")]
        [Required]
        public string fName { get; set; }
        [DisplayName("信箱")]
        [Required]
        [EmailAddress]
        public string fEmail { get; set; }
    }
}

接著寫控制器Controller

Using 剛剛做好的model

New一個資料庫物件出來

接著把tProduct表放進變數products

資料庫的資料先讀到index去

但沒有那麼簡單

必須要有登入與非登入的layout 用來存session

##今天要做第二個layout

首先先新增視圖Empty(without model)

但首先處理Index.cshtml ( 商品清單

@model IEnumerable 泛型

手刻bootstrap版

手刻 加入購物車的按鈕

先寫死的一次

再用foreach item 做所有的資料筆數

加入購物車的按鈕傳入當筆id藉由url傳遞到 action

接著必須判斷session才會出現 加入購物車的按鈕

接著回到Controller寫利用session判斷index的_layout

### 08ShoppingCar/Controllers/HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//01-1-3 using _08ShoppingCar.Models
using _08ShoppingCar.Models;

namespace _08ShoppingCar.Controllers
{
    public class HomeController : Controller
    {
        //01-1-4 使用Entity建立DB物件
        dbShoppingCarEntities db = new dbShoppingCarEntities();

        //01-2-1 在HomeController裡撰寫Index Action
        public ActionResult Index()
        {
            var products = db.tProduct.ToList();

            //若Session["Member"]為空,表示會員未登入
            if (Session["Member"] == null)
            {
                //指定Index.cshtml套用_Layout.cshtml,View使用products模型
                return View("Index","_Layout",products);
            }
            //會員登入狀態,指定Index.cshtml套用_LayoutMember.cshtml,View使用products模型
            return View("Index", "_LayoutMember", products);
        }
    }
}

###08ShoppingCar/Views/Home/Index.cshtml

@*//01-2-4 撰寫Index View,讀出資料,並以Bootstrap排版*@
@model IEnumerable<_08ShoppingCar.Models.tProduct>


@{
    ViewBag.Title = "產品列表";
}

<div class="row">
    @foreach (var item in Model)
    {
        <div class="col-md-4">
            <div class="thumbnail">
                <img src="~/images/@item.fImg" />
                <div class="caption">
                    <h2>@item.fName</h2>
                    <p>單價:@item.fPrice</p>
                    @if (Session["Member"] == null)
                    {
                        <p></p>
                    }
                    else
                    {
                        @*若Session["Member"]不為null才顯示此按鈕*@
                        <p><a href="@Url.Action("AddCar")?PId=@item.fPId" class="btn btn-danger">加入購物車</a></p>
                    }
                </div>
            </div>
        </div>
    }
</div>

###老師步驟

//00-1 利用Entity Framework建立Model(DB First)
//00-1-1 建立dbShoppingCar.mdb資料庫Model
//       在Models上按右鍵,選擇加入,新增項目,資料,ADO.NET實體資料模型,名稱輸入"dbShoppingCarModel",按新增
//       來自資料庫的EF Designer
//       連接dbShoppingCar.mdf資料庫,連線名稱不修改,按下一步按鈕
//       選擇Entity Framework 6.x, 按下一步按鈕
//       資料表全選, 按完成鈕
//       若跳出詢問方法按確定鈕
//00-1-2 在專案上按右鍵,建置
//00-2 修改Model
//00-2-1 在tMember.cs裡加入欄位名稱顯示(需using System.ComponentModel)與欄位驗證(需using System.ComponentModel.DataAnnotations)
//00-2-2 在tProduct.cs裡加入欄位名稱顯示(需using System.ComponentModel)
//00-2-3 在tOrder.cs裡加入欄位名稱顯示(需using System.ComponentModel)與欄位驗證(需using System.ComponentModel.DataAnnotations)
//00-2-4 在tOrderDetail.cs裡加入欄位名稱顯示(需using System.ComponentModel)


//01-1 建立HomeController
//01-1-1 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//01-1-2 指定控制器名稱為HomeController,並開啟HomeController
//01-1-3 using _08ShoppingCar.Models
//01-1-4 使用Entity建立DB物件
//01-2 製作Index頁面的顯示所有產品功能
//01-2-1 在HomeController裡撰寫Index Action
//01-2-2 在public ActionResult Index()上按右鍵,新增檢視,建立Index View
//01-2-3 進行下列設定:
//       View name:Index
//       Template:Empty(Without Model)
//       勾選Use a layout pages
//       按下Add
//01-2-4 撰寫Index View,讀出資料,並以Bootstrap排版

接著來改layout 改自動產生的碼

還有要改漢堡選單

一樣用helper html.actionlink

三版bootstrap用法

然後突然教了轉google搜尋引擎

接著在Shared新增一個新的layout

兩種view大家都可以用它? 一種是Layout

pasharedview ?? 下一個專案會告訴大家

接著做登入過後的 layout

漢堡選單內改為 登入過後的功能

然後稍微改了些bootstrap

### 08ShoppingCar/Views/Shared/_LayoutMember.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - 高屏澎東分署購物商城</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-default 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>
                @*//02-2-5 修改Brand*@
                @Html.ActionLink("線上購物車-會員專區", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                @*@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })*@
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("產品列表", "Index", "Home")</li>
                    <li>@Html.ActionLink("購物車", "ShoppingCar", "Home")</li>
                    <li>@Html.ActionLink("訂單", "OrderList", "Home")</li>
                    <li>@Html.ActionLink("登出系統", "Logout", "Home")</li>
                    <li><a href="#">@Session["WelCome"]</a></li>
                </ul>
                <form class="form-inline" action="https://www.google.com/search" method="get">
                    <div class="navbar-form">
                        <input id="Text1" type="text" name="q" placeholder="Please Input Something..." />
                        <input id="Submit1" type="submit" value="Search" class="btn btn-success" />
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - 高屏澎東分署購物商城</p>
        </footer>
    </div>

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

接著弄兩個action做登入一個用來post驗證一個用來get回傳值?

用simple bind就好因為只有帳號密碼

用linq lmada 寫查詢 查到就塞到變數 如果沒查到就不會塞

用viewbag傳帳號或密碼錯誤訊息到前端

如果驗證成功則 session帶入資料

且return redirecttoaction index

接著做登入的頁面 Login.cshtml

這裡有示範bind 但不知道是簡單還複雜

&錯誤訊息產生的方式

到此登入驗證帶session功能完成

###08ShoppingCar/Controllers/HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//01-1-3 using _08ShoppingCar.Models
using _08ShoppingCar.Models;

namespace _08ShoppingCar.Controllers
{
    public class HomeController : Controller
    {
        //01-1-4 使用Entity建立DB物件
        dbShoppingCarEntities db = new dbShoppingCarEntities();

        //01-2-1 在HomeController裡撰寫Index Action
        public ActionResult Index()
        {
            var products = db.tProduct.ToList();

            //若Session["Member"]為空,表示會員未登入
            if (Session["Member"] == null)
            {
                //指定Index.cshtml套用_Layout.cshtml,View使用products模型
                return View("Index","_Layout",products);
            }
            //會員登入狀態,指定Index.cshtml套用_LayoutMember.cshtml,View使用products模型
            return View("Index", "_LayoutMember", products);
        }

        //03-1-1 在HomeController裡分別撰寫Get與Post Login Action
        public ActionResult Login()
        {
            return View();
        }
        //03-1-1 在HomeController裡分別撰寫Get與Post Login Action
        [HttpPost]
        public ActionResult Login(string fUserId, string fPwd)
        {
            var member = db.tMember.Where(m => m.fUserId == fUserId && m.fPwd == fPwd).FirstOrDefault();
            if(member==null)
            {
                ViewBag.Message = "帳號或密碼錯誤!!";
                return View();
            }
            Session["WelCome"] = member.fName + "真正高興地見到你!";
            Session["Member"] = member;

            return RedirectToAction("Index");
        }
    }
}

###08ShoppingCar/Views/Home/Login.cshtml

@*//03-1-4 撰寫Login View*@
@{
    ViewBag.Title = "會員登入";
}

<h2>會員登入</h2>

<form accept-charset="@Url.Action("Login")" method="post">
    <div class="form-horizontal">
        <hr />
        <div class="form-group">
            <label for="fUserId" class="control-label col-md-2">帳號</label>
            <div class="col-md-10">
                <input id="fUserId" name="fUserId" type="text" class="form-control" required />
            </div>
        </div>
        <div class="form-group">
            <label for="fPwd" class="control-label col-md-2">密碼</label>
            <div class="col-md-10">
                <input id="fPwd" name="fPwd" type="password" class="form-control" required />
            </div>
        </div>
        <div class="form-group">

            <div class="col-md-10 col-md-offset-2">
                <input id="Submit1" type="submit" value="登入" class="btn btn-default" />
                <div class="alert-danger">@ViewBag.Message</div>
            </div>
        </div>
    </div>

</form>

###老師步驟

//00-1 利用Entity Framework建立Model(DB First)
//00-1-1 建立dbShoppingCar.mdb資料庫Model
//       在Models上按右鍵,選擇加入,新增項目,資料,ADO.NET實體資料模型,名稱輸入"dbShoppingCarModel",按新增
//       來自資料庫的EF Designer
//       連接dbShoppingCar.mdf資料庫,連線名稱不修改,按下一步按鈕
//       選擇Entity Framework 6.x, 按下一步按鈕
//       資料表全選, 按完成鈕
//       若跳出詢問方法按確定鈕
//00-1-2 在專案上按右鍵,建置
//00-2 修改Model
//00-2-1 在tMember.cs裡加入欄位名稱顯示(需using System.ComponentModel)與欄位驗證(需using System.ComponentModel.DataAnnotations)
//00-2-2 在tProduct.cs裡加入欄位名稱顯示(需using System.ComponentModel)
//00-2-3 在tOrder.cs裡加入欄位名稱顯示(需using System.ComponentModel)與欄位驗證(需using System.ComponentModel.DataAnnotations)
//00-2-4 在tOrderDetail.cs裡加入欄位名稱顯示(需using System.ComponentModel)


//01-1 建立HomeController
//01-1-1 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//01-1-2 指定控制器名稱為HomeController,並開啟HomeController
//01-1-3 using _08ShoppingCar.Models
//01-1-4 使用Entity建立DB物件
//01-2 製作Index頁面的顯示所有產品功能
//01-2-1 在HomeController裡撰寫Index Action
//01-2-2 在public ActionResult Index()上按右鍵,新增檢視,建立Index View
//01-2-3 進行下列設定:
//       View name:Index
//       Template:Empty(Without Model)
//       勾選Use a layout pages
//       按下Add
//01-2-4 撰寫Index View,讀出資料,並以Bootstrap排版


//02-1 修改Layout
//02-1-1 修改Views/Shared/_Layout.cshtml
//02-1-2 更改標頭與頁尾
//02-1-3 修改Brand
//02-1-4 加入選單
//02-2 建立Layout
//02-2-1 在View/Shared上按右鍵,新增檢視
//02-2-2 進行下列設定:
//       View name:_LayoutMember.cshtml
//       Template:Empty(Without Model)
//       不勾選Use a layout pages
//       按下Add
//02-2-3 將_Layout.cshtml內容複製至_LayoutMember.cshtml
//02-2-4 修改_LayoutMember.cshtml nav class內容
//02-2-5 修改Brand
//02-2-6 修改_LayoutMember.cshtml選單內容


//03-1 撰寫登入功能
//03-1-1 在HomeController裡分別撰寫Get與Post Login Action
//03-1-2 在public ActionResult Login()上按右鍵,新增檢視,建立Login View
//03-1-3 進行下列設定:
//       View name:Login
//       Template:Empty(Without Model)
//       勾選Use a layout pages
//       按下Add
//03-1-4 撰寫Login View

接著寫登出功能

清空session

寫在homecontroller.cs

ActionResult logout

會員登入 -> 進入index -> 資料庫資料

到此整個流程就串起來

接著做註冊帳號密碼

這裡多載用的是複雜繫結

首先先判斷驗證是否通過(modelstate.isvalid)

必須要用linq寫驗證是否重複

沒重複就寫入複雜繫結的物件

如果有重複則回傳錯誤訊息

接著新增註冊view

用帶model範本的view比較簡單因為用的是複雜繫結

砍掉一些不用的改掉一些要改得即可

###註冊帳號完成

###08ShoppingCar/Views/Home/Register.cshtml

@model _08ShoppingCar.Models.tMember

@{
    ViewBag.Title = "會員註冊";
}

<h2>會員註冊</h2>

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

        <div class="form-group">
            @Html.LabelFor(model => model.fPwd, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fPwd, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fPwd, "", 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">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="註冊" class="btn btn-default" />
            </div>
        </div>
    </div>
}

###08ShoppingCar/Controllers/HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//01-1-3 using _08ShoppingCar.Models
using _08ShoppingCar.Models;

namespace _08ShoppingCar.Controllers
{
    public class HomeController : Controller
    {
        //01-1-4 使用Entity建立DB物件
        dbShoppingCarEntities db = new dbShoppingCarEntities();

        //01-2-1 在HomeController裡撰寫Index Action
        public ActionResult Index()
        {
            var products = db.tProduct.ToList();

            //若Session["Member"]為空,表示會員未登入
            if (Session["Member"] == null)
            {
                //指定Index.cshtml套用_Layout.cshtml,View使用products模型
                return View("Index","_Layout",products);
            }
            //會員登入狀態,指定Index.cshtml套用_LayoutMember.cshtml,View使用products模型
            return View("Index", "_LayoutMember", products);
        }

        //03-1-1 在HomeController裡分別撰寫Get與Post Login Action
        public ActionResult Login()
        {
            return View();
        }
        //03-1-1 在HomeController裡分別撰寫Get與Post Login Action
        [HttpPost]
        public ActionResult Login(string fUserId, string fPwd)
        {
            var member = db.tMember.Where(m => m.fUserId == fUserId && m.fPwd == fPwd).FirstOrDefault();
            if(member==null)
            {
                ViewBag.Message = "帳號或密碼錯誤!!";
                return View();
            }
            Session["WelCome"] = member.fName + "真正高興地見到你!";
            Session["Member"] = member;

            return RedirectToAction("Index");
        }

        public ActionResult Logout()
        {
            Session.Clear();
            return RedirectToAction("Index");
        }

        public ActionResult Register()
        {

            return View();
        }

        [HttpPost]
        public ActionResult Register(tMember Member)
        {
            if (ModelState.IsValid == false)
            {
                return View();
            }

            var member = db.tMember.Where(m => m.fUserId == Member.fUserId).FirstOrDefault();
            if(member==null)
            {
                db.tMember.Add(Member);
                db.SaveChanges();

                return RedirectToAction("Login");
            }
            ViewBag.Message = "帳號已有人使用!!";
            return View();

        }

    }
}

###老師步驟

//00-1 利用Entity Framework建立Model(DB First)
//00-1-1 建立dbShoppingCar.mdb資料庫Model
//       在Models上按右鍵,選擇加入,新增項目,資料,ADO.NET實體資料模型,名稱輸入"dbShoppingCarModel",按新增
//       來自資料庫的EF Designer
//       連接dbShoppingCar.mdf資料庫,連線名稱不修改,按下一步按鈕
//       選擇Entity Framework 6.x, 按下一步按鈕
//       資料表全選, 按完成鈕
//       若跳出詢問方法按確定鈕
//00-1-2 在專案上按右鍵,建置
//00-2 修改Model
//00-2-1 在tMember.cs裡加入欄位名稱顯示(需using System.ComponentModel)與欄位驗證(需using System.ComponentModel.DataAnnotations)
//00-2-2 在tProduct.cs裡加入欄位名稱顯示(需using System.ComponentModel)
//00-2-3 在tOrder.cs裡加入欄位名稱顯示(需using System.ComponentModel)與欄位驗證(需using System.ComponentModel.DataAnnotations)
//00-2-4 在tOrderDetail.cs裡加入欄位名稱顯示(需using System.ComponentModel)


//01-1 建立HomeController
//01-1-1 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//01-1-2 指定控制器名稱為HomeController,並開啟HomeController
//01-1-3 using _08ShoppingCar.Models
//01-1-4 使用Entity建立DB物件
//01-2 製作Index頁面的顯示所有產品功能
//01-2-1 在HomeController裡撰寫Index Action
//01-2-2 在public ActionResult Index()上按右鍵,新增檢視,建立Index View
//01-2-3 進行下列設定:
//       View name:Index
//       Template:Empty(Without Model)
//       勾選Use a layout pages
//       按下Add
//01-2-4 撰寫Index View,讀出資料,並以Bootstrap排版


//02-1 修改Layout
//02-1-1 修改Views/Shared/_Layout.cshtml
//02-1-2 更改標頭與頁尾
//02-1-3 修改Brand
//02-1-4 加入選單
//02-2 建立Layout
//02-2-1 在View/Shared上按右鍵,新增檢視
//02-2-2 進行下列設定:
//       View name:_LayoutMember.cshtml
//       Template:Empty(Without Model)
//       不勾選Use a layout pages
//       按下Add
//02-2-3 將_Layout.cshtml內容複製至_LayoutMember.cshtml
//02-2-4 修改_LayoutMember.cshtml nav class內容
//02-2-5 修改Brand
//02-2-6 修改_LayoutMember.cshtml選單內容


//03-1 撰寫登入功能
//03-1-1 在HomeController裡分別撰寫Get與Post Login Action
//03-1-2 在public ActionResult Login()上按右鍵,新增檢視,建立Login View
//03-1-3 進行下列設定:
//       View name:Login
//       Template:Empty(Without Model)
//       勾選Use a layout pages
//       按下Add
//03-1-4 撰寫Login View


//04-1 撰寫會員註冊功能
//04-1-1 在HomeController裡分別撰寫Get與Post Register Action
//04-1-2 在public ActionResult Register()上按右鍵,新增檢視,建立Register View
//04-1-3 進行下列設定:
//       View name:Register
//       Template:Create
//       Model class:tMember(_08ShoppingCar.Models)
//       Data context class:dbShoppingCarEntities(_08ShoppingCar.Models)
//       勾選Use a layout pages
//       按下Add
//04-1-4 修改Register View, 改中文字, 加入@ViewBag.Message, 刪除Back to List

###剩下兩個主功能還沒完成 購物車crud 和訂單crud

禮拜五早上會講listView

包含 列出 加入 刪除 購物車內容

tOrderDetail

#購物車頁面 列出商品get 方法

只要仿照剛剛的index action 即可 ( index 裡面為商品清單

必須要傳入meber參數 因為只能看到自己的購物車

所以要用linq下查詢指傳回特定值

但因為剛剛Member是整個集合用複雜繫結所以要做預處理

接著把購物車資料丟入ShoppingCar()的View

然後要記得指定登入狀態的layout

空範本但

Model 用 tOrderDetail

增加view因為剛剛已經指定了所以layout不用再指定一次

接著到ShoppingCar.cshtml編輯view

一樣改範本必須要修改的

然後實作delete功能 ( url 傳遞

Ferter功能 ( 下個專案會講 ( 沒登入時報錯???

##接著實作加入購物車功能

新增一個 addcar把商品id傳入

然後用session抓會員帳號

邏輯是 按一次加入購物車 商品數量就會再加1 如我沒在購物車 放入預設為1

用linq去查詢看有沒有重複如果沒有這筆商品則

把產品id 會員id 數量 價格 商品名稱 狀態 丟入 model

如果已經被加入購物車則

則購物車內的商品+1

Db.SaveChanges()

Return shooppingcar

購物車完成2/3

出現bug 找很久 session其實要寫在ferter???會更好

接著寫 刪除 ( 獨立出一個 action 搜尋的是 fid所以要傳fid近來

把要刪掉的那筆找出來

然後從模型內先刪掉

真正update到資料庫

然後再return 到 shoppingcar 這樣 購物車功能即完成

把之前的crud加到商品 就變成商品管理 但是可能就要第三個layout

###08ShoppingCar/Controllers/HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//01-1-3 using _08ShoppingCar.Models
using _08ShoppingCar.Models;

namespace _08ShoppingCar.Controllers
{
    public class HomeController : Controller
    {
        //01-1-4 使用Entity建立DB物件
        dbShoppingCarEntities db = new dbShoppingCarEntities();

        //01-2-1 在HomeController裡撰寫Index Action
        public ActionResult Index()
        {
            var products = db.tProduct.ToList();

            //若Session["Member"]為空,表示會員未登入
            if (Session["Member"] == null)
            {
                //指定Index.cshtml套用_Layout.cshtml,View使用products模型
                return View("Index","_Layout",products);
            }
            //會員登入狀態,指定Index.cshtml套用_LayoutMember.cshtml,View使用products模型
            return View("Index", "_LayoutMember", products);
        }

        //03-1-1 在HomeController裡分別撰寫Get與Post Login Action
        public ActionResult Login()
        {
            return View();
        }
        //03-1-1 在HomeController裡分別撰寫Get與Post Login Action
        [HttpPost]
        public ActionResult Login(string fUserId, string fPwd)
        {
            var member = db.tMember.Where(m => m.fUserId == fUserId && m.fPwd == fPwd).FirstOrDefault();
            if(member==null)
            {
                ViewBag.Message = "帳號或密碼錯誤!!";
                return View();
            }
            Session["WelCome"] = member.fName + "真正高興地見到你!";
            Session["Member"] = member;

            return RedirectToAction("Index");
        }

        //05-1-1 在HomeController裡撰寫Logout Action
        public ActionResult Logout()
        {
            Session.Clear();
            return RedirectToAction("Index");
        }

        //04-1-1 在HomeController裡分別撰寫Get與Post Register Action
        public ActionResult Register()
        {

            return View();
        }
        //04-1-1 在HomeController裡分別撰寫Get與Post Register Action
        [HttpPost]
        public ActionResult Register(tMember Member)
        {
            if (ModelState.IsValid == false)
            {
                return View();
            }

            var member = db.tMember.Where(m => m.fUserId == Member.fUserId).FirstOrDefault();
            if(member==null)
            {
                db.tMember.Add(Member);
                db.SaveChanges();

                return RedirectToAction("Login");
            }
            ViewBag.Message = "帳號已有人使用!!";
            return View();

        }

        //06-1-1 在HomeController裡撰寫ShoppingCar Action
        public ActionResult ShoppingCar()
        {
            string fUserId = (Session["Member"] as tMember).fUserId;
            var orderDetails = db.tOrderDetail.Where(m=>m.fUserId== fUserId && m.fIsApproved=="否").ToList();

           
            return View("ShoppingCar", "_LayoutMember", orderDetails);
        }

        //06-3-1 在HomeController裡撰寫AddCar Action
        public ActionResult AddCar(string fPId)
        {
            string fUserId = (Session["Member"] as tMember).fUserId;

            //如果該商品已放在購物車中,則數量加1,若未在購物車中,則放入後預設數量為1
            var currentCar = db.tOrderDetail.Where(m => m.fUserId == fUserId && m.fIsApproved == "否" && m.fPId == fPId).FirstOrDefault();
            if(currentCar==null)
            {
                var product = db.tProduct.Where(m => m.fPId == fPId).FirstOrDefault();

                tOrderDetail orderDetail = new tOrderDetail();
                orderDetail.fUserId = fUserId;
                orderDetail.fPId = fPId;
                orderDetail.fQty = 1;
                orderDetail.fPrice = product.fPrice;
                orderDetail.fName = product.fName;
                orderDetail.fIsApproved = "否";
                db.tOrderDetail.Add(orderDetail);

            }
            else
            {
                currentCar.fQty += 1;
            }
            db.SaveChanges();


            return RedirectToAction("ShoppingCar");
        }

        //06-3-2 在HomeController裡撰寫DeleteCar Action
        public ActionResult DeleteCar(int fId)
        {

            var orderDetails = db.tOrderDetail.Where(m => m.fId == fId).FirstOrDefault();
            db.tOrderDetail.Remove(orderDetails);
            db.SaveChanges();

            return RedirectToAction("ShoppingCar");
        }
    }
}

###08ShoppingCar/Views/Home/ShoppingCar.cshtml

@model IEnumerable<_08ShoppingCar.Models.tOrderDetail>

@{
    ViewBag.Title = "購物車清單";
}

<h2>購物車清單</h2>

@*<p>
    @Html.ActionLink("Create New", "Create")
</p>*@
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.fOrderGuid)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fUserId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fPId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fPrice)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.fQty)
        </th>
        @*<th>
            @Html.DisplayNameFor(model => model.fIsApproved)
        </th>*@
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.fOrderGuid)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fUserId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fPId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fPrice)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fQty)
        </td>
        @*<td>
            @Html.DisplayFor(modelItem => item.fIsApproved)
        </td>*@
        <td>

            <a href="@Url.Action("DeleteCar")?fId=@item.fId" class="btn btn-danger">刪除商品</a>

            @*@Html.ActionLink("Edit", "Edit", new { id=item.fId }) |
            @Html.ActionLink("Details", "Details", new { id=item.fId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.fId })*@
        </td>
    </tr>
}

</table>

###老師步驟

//00-1 利用Entity Framework建立Model(DB First)
//00-1-1 建立dbShoppingCar.mdb資料庫Model
//       在Models上按右鍵,選擇加入,新增項目,資料,ADO.NET實體資料模型,名稱輸入"dbShoppingCarModel",按新增
//       來自資料庫的EF Designer
//       連接dbShoppingCar.mdf資料庫,連線名稱不修改,按下一步按鈕
//       選擇Entity Framework 6.x, 按下一步按鈕
//       資料表全選, 按完成鈕
//       若跳出詢問方法按確定鈕
//00-1-2 在專案上按右鍵,建置
//00-2 修改Model
//00-2-1 在tMember.cs裡加入欄位名稱顯示(需using System.ComponentModel)與欄位驗證(需using System.ComponentModel.DataAnnotations)
//00-2-2 在tProduct.cs裡加入欄位名稱顯示(需using System.ComponentModel)
//00-2-3 在tOrder.cs裡加入欄位名稱顯示(需using System.ComponentModel)與欄位驗證(需using System.ComponentModel.DataAnnotations)
//00-2-4 在tOrderDetail.cs裡加入欄位名稱顯示(需using System.ComponentModel)


//01-1 建立HomeController
//01-1-1 在Controllers資料夾上按右鍵,加入,控制器,選擇 MVC5Controller-Empty
//01-1-2 指定控制器名稱為HomeController,並開啟HomeController
//01-1-3 using _08ShoppingCar.Models
//01-1-4 使用Entity建立DB物件
//01-2 製作Index頁面的顯示所有產品功能
//01-2-1 在HomeController裡撰寫Index Action
//01-2-2 在public ActionResult Index()上按右鍵,新增檢視,建立Index View
//01-2-3 進行下列設定:
//       View name:Index
//       Template:Empty(Without Model)
//       勾選Use a layout pages
//       按下Add
//01-2-4 撰寫Index View,讀出資料,並以Bootstrap排版


//02-1 修改Layout
//02-1-1 修改Views/Shared/_Layout.cshtml
//02-1-2 更改標頭與頁尾
//02-1-3 修改Brand
//02-1-4 加入選單
//02-2 建立Layout
//02-2-1 在View/Shared上按右鍵,新增檢視
//02-2-2 進行下列設定:
//       View name:_LayoutMember.cshtml
//       Template:Empty(Without Model)
//       不勾選Use a layout pages
//       按下Add
//02-2-3 將_Layout.cshtml內容複製至_LayoutMember.cshtml
//02-2-4 修改_LayoutMember.cshtml nav class內容
//02-2-5 修改Brand
//02-2-6 修改_LayoutMember.cshtml選單內容


//03-1 撰寫登入功能
//03-1-1 在HomeController裡分別撰寫Get與Post Login Action
//03-1-2 在public ActionResult Login()上按右鍵,新增檢視,建立Login View
//03-1-3 進行下列設定:
//       View name:Login
//       Template:Empty(Without Model)
//       勾選Use a layout pages
//       按下Add
//03-1-4 撰寫Login View


//04-1 撰寫會員註冊功能
//04-1-1 在HomeController裡分別撰寫Get與Post Register Action
//04-1-2 在public ActionResult Register()上按右鍵,新增檢視,建立Register View
//04-1-3 進行下列設定:
//       View name:Register
//       Template:Create
//       Model class:tMember(_08ShoppingCar.Models)
//       Data context class:dbShoppingCarEntities(_08ShoppingCar.Models)
//       勾選Use a layout pages
//       按下Add
//04-1-4 修改Register View, 改中文字, 加入@ViewBag.Message, 刪除Back to List


//05-1 撰寫會員登出功能
//05-1-1 在HomeController裡撰寫Logout Action

//06-1 撰寫購物車功能
//06-1-1 在HomeController裡撰寫ShoppingCar Action
//06-1-2 在public ActionResult ShoppingCar()上按右鍵,新增檢視,建立ShoppingCar View
//06-1-3 進行下列設定:
//       View name:ShoppingCar
//       Template:List
//       Model class:tOrderDetail(_08ShoppingCar.Models)
//       Data context class:dbShoppingCarEntities(_08ShoppingCar.Models)
//       勾選Use a layout pages
//       按下Add
//06-2 修改ShoppingCar View
//06-2-1 修改英文字為中文
//06-2-2 刪除Create連結功能
//06-2-3 修改最後一欄為刪除所選商品功能
//06-3 撰寫加入商品至購物車與從購物車刪除商品功能
//06-3-1 在HomeController裡撰寫AddCar Action
//06-3-2 在HomeController裡撰寫DeleteCar Action

購物車完成但是訂單系統還沒 留到下一次

Last updated