2012-08-22 34 views
1

我目前工作的一個ASP.NET MVC 3項目,使用的模型屬性的允許快速視圖創建(如[Required]屬性,[DisplayName("foo")]等)DisplayFormat模型屬性變換串值

在這個項目中,我有一些日期存儲的值,例如格式爲「20120801」的字符串。

是否有使用屬性的方法:

[DisplayFormat(DataFormatString = "something")] 

或別的東西轉化到年月日YYYY-MM-DD。在我的示例中,顯示視圖「2012-08-01」而不是「20120801」。

感謝提前!

+0

嘗試答案張貼在這裏: http://stackoverflow.com/questions/5252979/assign-format-of-datetime-with-data-annotations – chris

回答

2

你需要更新你的模型看起來像這樣:

public class Person 
{ 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-mm-dd}")] 
    public DateTime DateOfBirth { get; set; } 
} 

你的控制器可能需要首先分析字符串:

public ActionResult Index() 
    { 
     Person p = new Person(); 
     p.DateOfBirth = DateTime.ParseExact("20120801","yyyyddmm",System.Globalization.CultureInfo.InvariantCulture); 

     return View(p); 
    } 

然後將其顯示在你看來,你將需要使用類似下面的代碼:

<fieldset> 
     <legend>Person</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.DateOfBirth) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.DateOfBirth) 
      @Html.ValidationMessageFor(model => model.DateOfBirth) 
     </div> 

     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 

出於某種原因,迪splayFormat屬性只能用於EditorFor和DisplayFor助手。

+0

硅它真的無法做出字符串值轉換? – eka808

+0

我已經相應地更新了示例代碼 – Deano

0

我結束了這個解決方案

[ScaffoldColumn(false)] 
public string MyValueFormattedAsYYYYMMDD { get; set; } 

public string MyValueAsFormattedDate 
{ 
    get 
    {    
     return MyClassToTransform.MyTransformMethod(this.MyValueFormattedAsYYYYMMDD); 
    } 
} 

使用這種方法,我「腳手架」(隱藏)未格式化的列,使屬性與getter以顯示格式的字符串。

您對此有何看法?