【发布时间】:2021-12-14 21:08:32
【问题描述】:
我有一个 Razor pages 网络应用程序,其中一个模型用于提供同事信息并包括他们的出生日期。
当我查看同事的脚手架页面时,出生日期字段填充在详细信息页面中,而不是编辑页面中。
下面的图片将说明我的意思。
这里是详细信息页面
这里是编辑页面
如您所知,由于编辑页面是空白的,如果我更改另一个字段,例如Staff Position 并保存,该同事的 DOB 变为 null。
正如我所说的页面来自 EF Core 脚手架,所以我相信表单的 HTML 应该是正确的。
编辑页面 HTML
<div class="form-group">
<label asp-for="Colleague.DateOfBirth" class="control-label"></label>
<input asp-for="Colleague.DateOfBirth" class="form-control" />
<span asp-validation-for="Colleague.DateOfBirth" class="text-danger"></span>
</div>
Colleague 是页面模型中Colleague 模型的绑定属性。如图所示,所有其他字段都很好。
更新
正如我所说,它使用的是模型绑定
[BindProperty]
public Colleague Colleague { get; set; }
邮递
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Attach(Colleague).State = EntityState.Modified;
try
{
selectedBranch = Colleague.BranchID;
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ColleagueExists(Colleague.ColleagueID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("../BranchColleagues", new { id = selectedBranch });
}
[DataType(DataType.Date)]
[Display(Name = "Date of Birth")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? DateOfBirth { get; set; }
【问题讨论】:
-
编辑表单最初是否正确填充?在你保存一个日期字段为空的更改之后?数据库中记录的列是否也为空?请向我们展示足够的代码来重现此场景。
-
嗨@Jasen 我添加了 OnPost 以显示保存时正在运行的内容。至于你关于数据库记录的问题。是的,它会覆盖。所以在显示的图像中,详细信息页面有一个 DOB,这也在 DB 中。如果我在编辑页面上保存而不填写 D.O.B,则 DB 中 D.O.B 的记录将更新为空
-
我之前也遇到过这个问题。在将
type="datetime-local"添加到日期时间的<input>中后,它会填充。据我所知,这是因为日期格式(UTC 或其他格式)不兼容。 -
好的,现在不确定问题。我只是仔细检查了模型,并决定通过注释掉这个注释来测试
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]注释掉已经解决了这个问题。编辑页面现在显示 DOB,它是本地格式,例如dd/MM/yyyy 而正如您想象的那样,对于数据库,它存储为 yyyy-MM-dd 。任何人都可以看到注释的问题以及为什么没有它现在可以工作? -
你所说的是什么意思,而正如你想象的那样,对于数据库,它存储为 yyyy-MM-dd"?模型属性的类型是什么?不是
DateTime并存储在数据库中(即键入的值,因此没有格式)?
标签: asp.net-core entity-framework-core razor-pages model-binding