ASP.NET MVC5 - Strongly Typed Model
@model Directive
為了解決 weakly typed 的問題, 通常因為 weakly typed 的 properties 大部分都是 string (
ViewData
), 或者是直到 runtime 才知道的 dynamic properties (ViewBag
), 如果裡面有 error, compile 的時候會不知道, 要等到 runtime 會知道
解決辦法:
@model List<Product>
下面這一行的 Model 就是上面所宣告的 model, 也就是 a list of Product
@foreach(var product in Model) {
}
使用範例 :
1.先去 Models folder create a class, 我這裡使用的是 Login.cs, 裡面有 2個 properties, 叫做 Username 和 Password
2.到 Views/Login/Index.cshtml 中拿到 Model 的 Username, Model? 表示是 optional, 如果沒有 Username 的話, default 就會是 null
3.到 LoginController 的 POST method 的 Index(), 傳入 Login 這一個 Model 作為參數
留言
張貼留言