![](/img/trans.png)
[英]ASP.NET MVC Core Web POST Request populating Data Model with NULL values
[英]Asp.net core MVC DatatTypes in model and null values
我有简单的 model MyModel:
[Key]
public int Id { get; set; }
public string 1stString { get; set; }
public string 2ndString { get; set; }
public string 3rdString { get; set; }
[DataType(DataType.Date)]
public DateTime MyDate { get; set; }
在我的 controller 然后我有:
[HttpGet]
public async Task<IActionResult> MyView(int? id)
{
var model = await _db.MyModel.ToListAsync(); ///HERE IT THROWS ERROR
ViewBag.Id = id ?? 1;
return View(model);
}
我有问题,我的 Db 中有 Null 值,所以我想它会因为日期时间而自动抛出此错误?
您必须从 DateTime 属性中删除 DataType 注释并使其为 Nullable
[Key]
public int Id { get; set; }
public string 1stString { get; set; }
public string 2ndString { get; set; }
public string 3rdString { get; set; }
public DateTime? MyDate { get; set; }
如果您只想获得日期,您可以使用以下方法装饰您的 ViewModel:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.