c# - EF Core 上输入字段的默认值
问题描述
我正在尝试使用 EF Core MVC 应用程序,但遇到了一个障碍:
我有一个具有如下 RenewDate 的模型(摘录):
[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; }
我还有一个 LicenceViewModel 专门用于将 STATUS (char(1)) 转换为字符串,如下所示:
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 ViewBag.AutoRenewDate = DateTime.Now.AddYears(1)
,以及在视图本身上使用 ViewData["AutoRenewDate"] 。我也试过public DateTime RENEWDATE{ get { return DateTime.Now.AddYears(1); } }
直接添加到viewModel,也无济于事。
我已经看到很多使用纯 Html 从 ViewBags 和 ViewModels 获取日期的答案,但我想知道是否有办法使用剃须刀页面模板来做到这一点......
编辑:我忘了明确指出这是“创建”表单页面,所以我没有填充模型来设置 RENEWDATE。我需要一个只读的表单字段,它会自动显示今天加上一年。
解决方案
我通过简单地忽略控制器脚本中的任何 POST 方法调用 viewmodel 并覆盖我需要在 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 });
}
推荐阅读
- android - Android 环境中未调用 aboutToQuit 信号?
- bdd - 如何让黄瓜为每个功能而不是每个场景实例化自定义世界?
- typescript - 有没有办法键入一个对象,以便扩展接口的所有属性都是给定的类型?
- sql - 两行相同但一列具有不同的值,如何将它们组合并摆脱另一行
- python - pymodbus 连接有时没有响应?
- installation - 跨多个系统的依赖关系
- list - 颤振将项目添加到列表
- python - 不确定当前的数据结构是否合适
- java - 如何获取主数组中子数组的值?
- maven - 有没有办法在 maven 的 pom.xml 文件中更新 package.json 中的版本(npm 版本次要)?