我有一个示例类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"
如果您这样输出,则实际上是ToString()
在对值进行运算。而是使用HTML帮助器:
@Html.DisplayFor(m => student.Date)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句