ASP.NET MVC - Creating Views, Controllers from Model Classes

CategoryId
  • 這會是一個 Foreign Key.
  • 前面的 ? 表示有或沒有都可以
  • default, EF會用 cascade, 所以可以刪除 foreign key
Category
  • 叫做 navigation property.
  • 可以代表別的 entity
  • 設為 virtual 是為了可以使用 Lazy Loading

Database Context
這一個 context class 繼承 System.Data.Entity.DbContext
這一個 context class 一個 db 大部分都會有一個
context class 裡面會有很多 DbSet, 這一個 DbSet 也是 Entity Set
DbSet == db 裡面的 table
DbSet : 表示告訴 EF 用 Product class 代表 db 裡面的 Products table 裡面的其中一個 row

[HttpPost] : 如果 request 傳的 method 是 post request
[ValidateAntiForgeryToken] :
  • 確保這一個 request 是由 HTML form 所 trigger 的
  • prevent xss
  • xss : 會從別的 form 傳 request 直接到你的 web application 上
([Bind(Include = “ID,Name”)] Category category)
  • 當加一個新的 category, 告訴這一個 method 只要包含 Id 和 Name properties
  • prevent overposting attacks
  • overposting attacks 例子 : 假設現在買了一台電腦, 電腦很貴要 1800000, 但是如果使用 overposting attack, 可以在傳送 form 裡面的 price 變成 $18

這一個 view 是遵照 這一個 model 所製造出來
在 CategoriesController 的 Index method 會傳 一連串的 categories 到 Index view
這樣子 view 就可以拿到這一串 categories
所以這一個 model implement IEnumerable interface and the type is category

相等於 html 的 <a href="/create">Create New</a>

因為有拿到一連串的 categories, 所以如果要顯示 Name, 就可以使用
@Html.DisplayNameFor(model => model.Name)

Category create
The first new feature used is the code @Using(Html.BeginForm()), which tells the
view to wrap everything inside this using statement in an HTML form.
相等於 html 的

可以跟 controller 的 [ValidateAntiForgeryToken] 做double check
@Html.AntiForgeryToken() then generates an anti-forgery token, which is
checked for a match by the POST version of the Create method (using the[ValidateAntiForgeryToken] attribute).

這是一個 SelectList, 裡面包含了 db 裡面全部的 categories
Name:在 view 要顯示的是哪一個 property, 這裡是 category name
Id: 要用甚麼辨別 user 選擇哪一個 category, 這裡選的是 category id

留言

這個網誌中的熱門文章

ASP.NET Web API - DTOs

Scaffold Identity into the Current Project

Passing data from controller to the view