C# 使用DisplayFormat时,视图中的日期未格式化
我有一个示例类C# 使用DisplayFormat时,视图中的日期未格式化,c#,asp.net-mvc,asp.net-mvc-4,razor,C#,Asp.net Mvc,Asp.net Mvc 4,Razor,我有一个示例类Student,其格式化属性为DateTime?type,仅将日期显示为dd/MM/yyyyy。代码片段如下所示: public partial class Student { // ... public DateTime? Date { get; set; } } [MetadataType(typeof(StudentMetaData))] public partial class Student { } public class StudentMetaDa
Student
,其格式化属性为DateTime?
type,仅将日期显示为dd/MM/yyyyy
。代码片段如下所示:
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; }
}
我将集合列表
中的所有学生作为模型发送到一个视图并读取记录,但是日期
属性的格式不是我想要的。此外,当特定字段中的日期缺失时,它不会提供文本。我还需要设置其他属性吗?这是视图中的代码:
@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>
@使用MvcDbContext.Models
@模型列表
@{
ViewBag.Title=“学生名单”;
}
学生名单
@foreach(模型中的学生)
{
@student.StudentName
@学生,性别
@学生,日期
}
这是输出:
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"
Adam Male 2012年5月7日00:00:00如果这样输出,则实际上是在对值执行ToString()
。而是使用Html帮助程序:
@Html.DisplayFor(m => student.Date)