iT邦幫忙

2021 iThome 鐵人賽

DAY 19
1
自我挑戰組

C# 學習之旅系列 第 19

ASP.NET MVC 從入門到放棄(Day19)-MVC模型(Model)介紹

  • 分享至 

  • xImage
  •  

接下來講講Model 部分...

簡單來說Model負責與資料庫溝通的相關邏輯,或者定義模板(.cs),或是使用Entity Framework自動產生資料庫對應的模板(類別(.cs))後...交給Controoler去處理..

Category.cs 類別檔

public class Category
{

   public int CateType { get; set; }
   public string CategoryID { get; set; }
   public string CategoryName { get; set; }

   public Category()//建構值
   {

   }

   public static List<Category> Get_Gategory(int id)
   {

            List<Category> result = new List<Category>();
            string connectionString = GlobalFunction.GlobalConnString;

            using (var conn = new MySqlConnection(connectionString))
            {

                conn.Open();

                using (var command = conn.CreateCommand())
                {
                    command.CommandText = "SELECT Category, Category_Name FROM Category WHERE CateType = @CateType";
                    command.Parameters.AddWithValue("@CateType", id);

                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                result.Add(new Category()
                                {
                                    CategoryID = (string)reader["Category"],
                                    CategoryName = (reader.IsDBNull(reader.GetOrdinal("Category_Name"))) ? "" : (string)reader["Category_Name"],
                                });
                            }
                            return result;
                        }
                        else
                        {
                            return result;
                        }
                    }
                }
            }
        }
}

上方public string CategoryName 就是類別檔的模板, 接著再用Get_Gategory函式使用Ado 連線存在List 回傳給Controoler

小幫手:如果要快速生成屬性(property)

   public int CateType { get; set; } 

可以在類別檔加入prop 按2次Tab鍵即可

補充說明:如果使用.Net6版本 屬性(property) 預設要加入? (?代表允許Null)

   public int? CateType { get; set; } 

且顯示畫面Model要加入!

   @Model!.CateType

CategoryController.cs 控制器

public ActionResult Index(string id){
    var category = Category.Get_Category(id);
    return View(category);
}

Controoler收到資料後再透過return View() 將List資料丟給顯示畫面

Index.cshtml 顯示畫面

@model IEnumerable<WebApplication1.Models.Category.Category>
<table class="table">
    <tr>
        <th width="70">
            操作
        </th>
        <th width="70">
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().CategoryID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().CategoryName)
        </th>
        <th>

        </th>
    </tr>
    @foreach (var md in this.Model)
    {
        <tr>
            <td>
                @Html.ActionLink("編輯", "Edit", new { Type = ViewBag.Type, categoryID = md.CategoryID }, new { @class = "glyphicon glyphicon-pencil" })
            </td>
            <td>

                @Html.ActionLink("刪除", "Delete", new { Type = ViewBag.Type, categoryID = md.CategoryID }, new { @class = "glyphicon glyphicon-trash", @onclick = "return Confirm_Form('"+ md.CategoryID + "')" })
            </td>
            <td>@md.CategoryID</td>
            <td>@md.CategoryName</td>
        </tr>
    }
</table>

Model Class加入寫法

Class1.cs 類別檔

    public class Class1
    {
        public string Test1 { get; set; }
    }

Controller 傳統寫法


   Models.Class1 myClass = new Models.Class1();     
   myClass.Test1 = "Yaowen";

Controller 中期寫法

    Models.Class1 myClass = new Models.Class1
   {
    
      myClass.Test1 = "Yaowen";
   };

VS2022的簡化寫法

    Models.Class1 myClass = new ()
   {
    
      myClass.Test1 = "Yaowen";
   };

上一篇
ASP.NET MVC 從入門到放棄(Day18)-MVC檢視(View)介紹
下一篇
ASP.NET MVC 從入門到放棄(Day20) -MVC模型(Model) Entity Framework
系列文
C# 學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
noway
iT邦研究生 3 級 ‧ 2022-02-03 10:34:29

您好: 請問

  1. string connectionString = GlobalFunction.GlobalConnString;

        using (var conn = new MySqlConnection(connectionString))
    

這兩段,是由哪邊設定?

  1. 另外,public static List Get_Gategory(int id)
    但您 卻使用 var category = Category.Get_Category(SearchString, type);
    多一個參數,這樣正確嗎?

  2. 且顯示畫面Model要加入! @Model!.CateType
    這是指,要從哪邊加入?? View 沒有看到這一段
    謝謝!

Yaowen iT邦研究生 4 級 ‧ 2022-02-03 11:38:39 檢舉

1.GlobalFunction.GlobalConnString
我有另外拉出來放在別的地方方便不用重複寫參數
2.多一個參數 我多寫了...
3.@Model!.CateType 這個是.Net6版本 要求判斷null 但這次專案是以ASP.Net MVC5 Framework4.7.2為主

以下為Code
https://github.com/Yaowen77/aspmvcweb

我要留言

立即登入留言