2017年9月4日 星期一

ASP.NET MVC DisplayTemplates

範本檔案放置的路徑是固定的

    /Views/ControllerName/DisplayTemplates
    /Views/Shared/DisplayTemplates

檔名需要與物件的型別相同,即若物件型別為 DateTime,則檔名需為 DateTime,或在
Model 上以 [UIHint("YourDisplayTemplatesName")] 標籤指定顯示範本的檔名

選定檢視範本的方式有三種,其順序為
1.UIHine 屬性
2.DataType 屬性
3.物件的資料型別名稱(不含命名空間)

蠻適合拿來處理西元轉民國年問題
在處理檢示範本頁面上需要注意會不會傳入的值是 null 的問題

實作方式

在 /Views/Shared/DisplayTemplates 中加入 twDateTime.cshtml
可能需要自行建立 DisplayTemplates 資料夾
這頁就是檢視範本,最後輸出什麼到 View 上就是看這頁最後會產出什麼

  1. @model DateTime
  2. @using System.Globalization
  3. @{
  4. TaiwanCalendar tc = new TaiwanCalendar();
  5. }
  6. @tc.GetYear(Model)/@tc.GetMonth(Model)/@tc.GetDayOfMonth(Model)

在 Model 中加入 DTTest.cs

  1. public class DTTest
  2. {
  3. [UIHint("twDateTime")]
  4. [DataType(DataType.DateTime)]
  5. public DateTime Dt { get; set; }
  6. }

在 Controller 中加入

  1. public ActionResult ShowTWDt()
  2. {
  3. var DTTest = new DTTest()
  4. {
  5. Dt = DateTime.Now
  6. };
  7.  
  8. return View(DTTest);
  9. }

在 View 中加入 ShowTWDt.cshtml
    @model ControllerPratice.Models.DTTest
    @Html.DisplayFor(model => model.Dt)

沒有留言:

張貼留言