2010-07-14 37 views
2

我的.dbml有LINQ的命名DExamination.dbmlLINQ到SQL - 格式的DateTime在Html.TextBoxFor

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Examination")] 
public partial class Examination : INotifyPropertyChanging, INotifyPropertyChanged 
{ 

    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); 

    private int _Id; 

    private string _Title; 

    private System.Nullable<System.DateTime> _StartDate; 
} 
... 
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_StartDate", DbType="DateTime")] 
    public System.Nullable<System.DateTime> StartDate 
    { 
     get 
     { 
      return this._StartDate; 
     } 
     set 
     { 
      if ((this._StartDate != value)) 
      { 
       this.OnStartDateChanging(value); 
       this.SendPropertyChanging(); 
       this._StartDate = value; 
       this.SendPropertyChanged("StartDate"); 
       this.OnStartDateChanged(); 
      } 
     } 
    } 
... 

顯示在編輯SQL類

<%: Html.TextBoxFor(model => model.Examination.StartDate)%> 

如何格式化開始日期,如「 DD/MM/YYYY」

上面我已經試過加DisplayFormat ...

[global::System.ComponentModel.DataAnnotations.DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] 
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_StartDate", DbType="DateTime")] 
    public System.Nullable<System.DateTime> StartDate 
    { 
     get 
     { 
      return this._StartDate; 
     } 
     set 
     { 
      if ((this._StartDate != value)) 
      { 
       this.OnStartDateChanging(value); 
       this.SendPropertyChanging(); 
       this._StartDate = value; 
       this.SendPropertyChanged("StartDate"); 
       this.OnStartDateChanged(); 
      } 
     } 
    } 

但無法正常工作

任何人都有解決方案嗎?

回答

0

您可以在Shared視圖目錄下創建一個目錄EditorTemplates。 然後添加一個名爲DateTime.ascx用下面的代碼控制:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %> 
<%:Html.TextBox(string.Empty,Model.ToString("dd/MM/yyyy")) %> 

然後你就可以用

<%: Html.EditorFor(model => model.Examination.StartDate) %> 
+0

謝謝! 它工作正常 – user384241 2010-07-15 01:41:48

+0

這將適用於**每個** DateTime模型屬性,您選擇使用'EditorFor',我從海報的評論中獲取它是他正在尋找的。但是,如果您想有條件地將自定義編輯器/顯示模板應用於一個或多個模型屬性,則可以使用將templateName作爲參數的'EditorFor/DisplayFor'覆蓋。 – 2014-08-25 17:21:13

1

你需要來裝飾你的模型:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] 
public DateTime StartDate{ get; set; } 

和屬性已經存在在你的代碼,只是錯誤的順序。

+0

改變了我的答案調用它。 – 2010-07-14 12:43:12

-1

你試過:

<%: Html.TextBoxFor(model => model.Examination.StartDate.ToString("dd/MM/yyyy"))%> 
+0

這將無法正常工作,html助手擴展只接受屬性作爲參數 – Gregoire 2010-07-14 11:56:20