DateTime和DateTimeOffset转换问题

时间:2019-06-21 15:24:10

标签: c# datetime datetimeoffset

我的ModelState总是被设置为无效,因为我的一个模型中的CreatedAt值总是以Dates / ############# /的形式返回,这导致空值。我想知道为什么会这样。 CreatedAt是DateTimeOffset。我相当确定它应该从另一个数据库表中提取DateTimeOffset值。

我尝试将其强制转换为日期时间,创建一个新的DateTimeOffset并将其传入,然后仅传递DateTimeOffset.Now使其生效。没有一个起作用。

public ActionResult EditSafetyIncidentPopUp([DataSourceRequest] DataSourceRequest request, SafetyIncidentViewModel sivm)
{
    if (sivm != null && ModelState.IsValid)
    {
        SafetyIncident si = new SafetyIncident
        {
            Id = sivm.Id,
            CreatedAt = new DateTimeOffset(sivm.CreatedAt),
            Description = sivm.Description,
            Type = sivm.Type,
            ProductionLineId = sivm.ProductionLineId,
            ProdLine = _productionLineService.Find(sivm.ProductionLineId)
        };

        _safetyIncidentService.Update(si);
    }

    return this.Json(new[] { sivm }.ToDataSourceResult(request,ModelState));}


public class SafetyIncidentViewModel
{
    public string Id { get; set; }
    [Required]
    [ReadOnly(true)]
    public DateTime CreatedAt { get; set; }
    [Required]
    public string Description { get; set; }
    [Required]
    [Range(0, 1, ErrorMessage = "Enter a valid type.")]
    public type Type { get; set; }
    [Display(Name = "Production Line")]
    [Required]
    public string ProductionLineId { get; set; }
    [Display(Name = "Production Line")]
    public ProductionLine ProdLine { get; set; }
}

我希望结果成功更新我的数据库。当前,它仅更新网格,然后由于ModelState无效而无法将数据传递到数据库。

1 个答案:

答案 0 :(得分:0)

更改视图模型以使用日期时间偏移而不是DateTime。则无需进行转换。