Razor Page ignores DisplayFormat



我在一个模型中保存一个日期:

[Display(Name = "Eintrittsdatum")]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = false)]
[Required]
public DateOnly EntryDate { get; set; }

但是当我试图在视图中显示它时,它会这样做。不管DisplayFormat行是否存在,或者它在那里说什么,我可以写任何东西,程序完全忽略那行。

经过一番搜索,我找到了这个解决方案。

现在我的日期正确显示,但在一个可编辑的文本框中,这不是我真正想要的。有没有人有更好的解决办法或者解释为什么我的约会对象长得像第一张图?

Index.cshtml:

@foreach (var item in Model.Employee)
{
...
<td>
@Html.TextBoxFor(modelItem => item.EntryDate, "{0:dd.MM.yyyy}", new {maxLength = 10})
</td>
<td>
@Html.DisplayFor(modelItem => item.Salary)
</td>
...

Index.cs:

public class IndexModel : PageModel
{
private readonly PersonaleinstellungContext _context;
public IndexModel(PersonaleinstellungContext context)
{
_context = context;
}
public IList<Employee> Employee { get; set; }
[BindProperty(SupportsGet = true)]
public string SearchString { get; set; }
public SelectList Departments { get; set; }
[BindProperty(SupportsGet = true)]
public string EmpDepartment { get; set; }
public async Task OnGetAsync()
{
IQueryable<string> depQuery = from e in _context.Employee
orderby e.Department
select e.Department;
var employees = from e in _context.Employee
select e;
if (!string.IsNullOrEmpty(SearchString))
{
employees = employees.Where(s => s.LName.Contains(SearchString));
}
if (!string.IsNullOrEmpty(EmpDepartment))
{
employees = employees.Where(x => x.Department == EmpDepartment);
}
Departments = new SelectList(await depQuery.Distinct().ToListAsync());
Employee = await employees.ToListAsync();
}
}

要格式化DateTime的显示,您可以简单地为ToString方法提供一个格式字符串(以及薪水):

@foreach (var item in Model.Employee)
{
<td>
@item.EntryDate.ToString("dd.MM.yyyy")
</td>
<td>
@item.Salary.ToString("c")
</td>
...

另一件事-不要使用Html帮助在ASP中呈现表单字段。净的核心。使用标记帮助器代替。设置DataTypeDate,格式字符串input type="date"理解一个ISO 8601字符串,ApplyFormatInEditModetrue,让剃须刀页面其余的照顾:

[Display(Name = "Eintrittsdatum")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DateType.Date)]
[Required]
public DateOnly EntryDate { get; set; }

<input asp-for="EntryDate" />

https://www.learnrazorpages.com/razor-pages/forms/dates-and-times

最新更新