Linq to SQL - 在Html.TextBoxFor中格式化DateTime

时间:2010-07-14 11:32:28

标签: c# asp.net asp.net-mvc

我有.dbml Linq到SQL类名为DExamination.dbml

[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();
            }
        }
    }
...

在编辑中显示

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

如何格式化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();
            }
        }
    }

但没有工作

有人有解决方案吗?

3 个答案:

答案 0 :(得分:1)

你需要装饰你的模型:

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

该属性已存在于您的代码中,只是错误的顺序。

答案 1 :(得分:0)

您可以在EditorTemplates视图目录中创建目录Shared。 然后使用以下代码添加名为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) %>

答案 2 :(得分:-1)

你试过了吗?

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