2015年4月22日 星期三

DisplayTemplates & EditorTemplates

在mvc中,我們可以為特定型別定義模板

當在razor語法中,用某些語法呼叫該型別時,會自動對應到Shared資料夾下的模板來顯示


@Html.DisplayFor ->Shared/DisplayTemplates/型別名稱
@Html.EditorFor->Shared/EditorTemplates/型別名稱

例如,當我們在razor中使用@Html.DisplayFor(m=>m.myText),myText是string型別時,會使用Shared/DisplayTemplates/String.cshtml來取代該字串的顯示

以上的模板是針對網站上所有該型別的資料,如果只是想要讓特定幾筆資料使用模板,可以將Shared/DisplayTemplates/下的String.cshtml改名,然後再到model使用的型別上定義要使用的模板


如String.cshtml->MyString.cshtml

model class

[UIHint("MyString")]
public string myText{ get; set;}



2015年4月20日 星期一

MVC migration command

在Package Manager Console(nuget套件管理員->套件管理器主控台)下輸入
Enable-Migrations - ContextTypeName 開啟該資料表的migration
這個指令會產生 Migrations 資料夾,其中包含 Configuration.cs 檔案
Configuration.cs中的Seed function可以輸入進行migration時要建立的資料
add-migration Initial 重新產生資料表
add-migration 欄位名稱 新建欄位
最後輸入update database即可更新資料表,此時會連帶建立Seed()中定義的資料 add-migration DataAnnotations 可更新資料欄位的定義(格式 長度限制等)

2015年4月19日 星期日

MVC 日期顯示方式(Model中的日期參數)

DateTime在View中使用Model.DateTime來綁定的話,預設會顯示yyyy/MM/dd hh/mm/ss 想要修改顯示方式的話,可以在參數上加上這行 [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

MVC 防範CSRF攻擊

轉載http://kevintsengtw.blogspot.tw/2013/01/aspnet-mvc-validateantiforgerytoken.html