gpt4 book ai didi

c# - 使用 DisplayFormat 时未在 View 中设置日期格式

转载 作者:行者123 更新时间:2023-11-30 20:24:23 27 4
gpt4 key购买 nike

我有一个示例类 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属性的格式不符合我的要求。此外,当特定字段中的日期缺失时,它不会提供文本。我还需要设置其他属性吗?这是 View 中的代码:

@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)

关于c# - 使用 DisplayFormat 时未在 View 中设置日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26926586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com