2010-07-14 38 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