EF Core 上输入字段的默认值



我正在尝试使用 EF Core MVC 应用程序,但遇到了一个障碍:

我有一个模型,其续订日期如下(摘录(:

[Required]
[Display(Name = "Status")]
public char STATUS { get; set; }
[Required]
[Display(Name = "Licence Renew Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime RENEWDATE { get; set; }

我还有一个专门用于将状态(char(1((转换为字符串的LicenceViewModel,如下所示:

public class LicencaViewModel
{
public Licence Licence { get; set; }
public string Status 
{
get 
{
return Licence.STATUS switch
{
'P' => "Pending",
'I' => "Inactive",
'B' => "Blocked",
'A' => "Active",
_ => "Error"
}; 
}
set 
{
Licence.STATUS = value switch
{
"Pending" => 'P',
"Inactive" => 'I',
"Blocked" => 'B',
"Active" => 'A',
_ => 'P'
};
}
}
}

最后,Create.cshtml的相关行:

<div class="form-group">
<label asp-for="Licence.RENEWDATE" class="control-label"></label>
<input asp-for="@DateTime.Now" readonly type="date" class="form-control" />
<span asp-validation-for="Licence.RENEWDATE" class="text-danger"></span>
</div>

因此,基本上我在这里要实现的是一个只读字段,该字段仅显示客户许可证的自动设置续订日期。它现在的方式只是显示当前日期,但我不能使用@DateTime.Now.AddYears(1)因为我得到Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

我尝试在控制器上使用带有ViewBag.AutoRenewDate = DateTime.Now.AddYears(1)的ViewBag,以及在视图本身上使用ViewData["AutoRenewDate"]。我也尝试将public DateTime RENEWDATE{ get { return DateTime.Now.AddYears(1); } }直接添加到视图模型中,也无济于事。

我已经看到很多使用纯 HTML 从 ViewBag 和 ViewModel 获取日期的答案,但我想知道是否有办法使用剃须刀片页面模板来做到这一点......

编辑:我忘了明确这是"创建"表单页面,所以我没有将RENEWDATE设置为填充模型。我需要一个只读表单字段,该字段在今天加上一年内自动显示。

我通过简单地忽略控制器脚本中 POST 方法调用视图模型的任何内容并覆盖我需要在 POST 方法上设置为默认值的属性来解决此问题,如下所示:

[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin, manager")]
public async Task<IActionResult> Create(LicencaViewModel licencaViewModel)
{
if (!ModelState.IsValid) return View(licencaViewModel);
licencaViewModel.Licence.STATUS = 'P'; //This overrides whatever licencaViewModel currently has and sets it to the expected value.
string serial = await _licencaViewModelService.InsertAsync(licencaViewModel.Licenca);
return RedirectToAction("Details", new { id = serial });
}

最新更新