使用DisplayFormat时,日期未在View中格式化

时间:2014-11-14 09:19:45

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

我有一个示例类Student,其格式为DateTime?类型的属性,仅将日期显示为dd/MM/yyyy。代码段如下:

public partial class Student
{
    // ...
    public DateTime? Date { get; set; }
}

[MetadataType(typeof(StudentMetaData))]
public partial class Student
{
}

public class StudentMetaData
{
    // ...
    [DisplayFormat(
        DataFormatString = "{0:dd/MM/yyyy}", 
        ApplyFormatInEditMode=true, 
        NullDisplayText="Date's not provided")]
    public DateTime? Date { get; set; }
}

我将集合List<Student>中的所有学生作为模型发送到视图并阅读记录,但Date属性未按我的要求格式化。此外,当缺少特定字段中的日期时,它不提供文本。我还需要设置其他属性吗?这是视图中的代码:

@using MvcDbContext.Models
@model List<Student>
@{
    ViewBag.Title = "List of Students";
}
<h2>List of Students</h2>
<table>
    @foreach (Student student in Model)
    {
        <tr>
            <td>
                @student.StudentName
            </td>
            <td>
                @student.Gender
            </td>
            <td>
                @student.Date
            </td>
        </tr>
    }
</table>

这是输出:

Adam     Male    07/05/2012 00:00:00  <- Date's not been formatted
Alex     Female  09/11/2014 00:00:00
Angela   Female  24/12/2011 00:00:00
Chris    Male                         <- here's supposed to be info "Date's not provided"
Clint    Male                         <- here's supposed to be info "Date's not provided"

1 个答案:

答案 0 :(得分:6)

如果你这样输出,你基本上对值进行ToString()。而是使用Html助手:

@Html.DisplayFor(m => student.Date)