[ 私人小抄 ] ASP.NET MVC UIHint

筆記一下 UIHint

案例 : 當 mongoDB 的 ObjectId 型別 要在view 上呈現的時候 
直接 DisplayFor 出來的內容 會像是
Timestamp
1600067111
Machine
16521111
Pid
3111
Increment
3328111
CreationTime
2020/11/11 上午 11:11:11

可是 實際上的內容 會像是GUID的格式
嘗試加上 ToString 就會出現以下錯誤
System.InvalidOperationException: '範本只能配合欄位存取、屬性存取、單一維度陣列索引或單一參數自訂索引子運算式使用。'

這時候 就可以用 UIHint ( DisplayTemplates )
在 Views > Shared> 新增 DisplayTemplates 資料夾
新增檔案 EX : ObjectIdString.cshtml

@model ObjectId
@Model.ToString()

使用上 有兩個方式 
在class 屬性上 加上 [UIHint("ObjectIdString")]
或是 在view 用  @Html.DisplayFor(modelItem => item.Id, "ObjectIdString")
 

參考
認識View - DisplayTemplates與EditorTemplates補充
ASP.NET MVC - 下拉選單的日期選擇器 Part.5 - Editor Templates

如果內容有誤請多鞭策謝謝