ASP.NET 使用 cshtml 作為單一網頁解決方案


  1. 說明
    1. Layout
    2. Body

說明在微網頁開發上,不使用 ASP.NET MVC 完整的架構,如何單純以 cshtml 檔案的方式取代 asp classic 以及 aspx,使用熟悉的 razor 語言完成網頁編輯與改寫的工作。

logo

說明

建立專案,使用「ASP.NET 空白網站」。

Layout

可以使用 Razor 的 Layout 抽出重複出現的程式碼 😁

/Layout.cshtml

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="description" content="" />
    <meta name="author" content="" />
    <title>Simple Sidebar - Start Bootstrap Template</title>
    <!-- Favicon-->
    <link rel="icon" type="image/x-icon" href="assets/favicon.ico" />
    <!-- Core theme CSS (includes Bootstrap)-->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
    <div class="d-flex" id="wrapper">
        <!-- Page content-->
        @RenderBody()
    </div>
    <!-- Bootstrap core JS-->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Body

/WebPage.cshtml

@using Dapper
@using System.Data.SqlClient
@{
    Layout = "~/Layout.cshtml";

    IEnumerable<dynamic> model = null;

    var connectionString = "data source=(localdb)\\MSSQLLocalDB;initial catalog=Northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";

    using (var cn = new SqlConnection(connectionString))
    {
        cn.Open();
        model = cn.Query($@"SELECT C.CategoryName, P.ProductID, P.ProductName 
            FROM [Northwind].[dbo].[Categories] AS C 
            JOIN Products AS P ON C.CategoryID = P.CategoryID");
    }
}

<div class="container-fluid">
    <h1 class="mt-4">Simple Sidebar</h1>
    <p>lorem ipsum</p>

    <table class="table table-bordered table-striped">
        <tr>
            <th>Category</th>
            <th>Product</th>
        </tr>
        @foreach (var row in model)
        {
            <tr>
                <td>@row.CategoryName</td>
                <td>@row.ProductName (@row.ProductID)</td>
            </tr>
        }
        
        @model.First()
    </table>
</div>

真正的網頁內容,包含了資料庫連線、查詢語法以及組織 HTML,類似以往的 asp classic,但使用 Razor 語法寫起來更為流暢。

使用 Dapper 作為資料存取技術,不需要使用 Model,使用 Dynamic 的方式處理資料,寫起來有如 Python 那麼便利。