[英]DateTime in the transfer parameter of the edit method in the controller is always 01.01.0001 00:00:00 asp.net mvc5
I a problem in the transfer parameter in the Edit Method "issue".我在编辑方法“问题”中的传输参数有问题。
In Issue the CreatedDate and UpdatedDate is always {01.01.0001 00:00:00}.在 Issue 中,CreatedDate 和 UpdatedDate 始终为 {01.01.0001 00:00:00}。
The parameter Id, Title and Description is always correct.参数 Id、Title 和 Description 总是正确的。
My Controller:我的 Controller:
public ActionResult Edit([Bind(Include = "Id,Title,Description")] Issue issue)
{
if (ModelState.IsValid)
{
db.Entry(issue).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(issue);
}
My Model:我的 Model:
public class Issue : BaseEntity
{
public int Id { get; set; }
[Required(ErrorMessage = "Required")]
public string Title { get; set; }
[AllowHtml]
[Required(ErrorMessage = "Required")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
}
public class BaseEntity
{
public DateTime CreatedDate { get; set; }
public DateTime UpdatedDate { get; set; }
}
I can unfortunately can not debug from where the "issue" parameter comes from.不幸的是,我无法调试“问题”参数的来源。
From where the transfer parameter "Issue issue" in the Edit method comes from and why are all DateTimes always {01.01.0001 00:00:00}? Edit方法中的传输参数“Issue issue”从何而来,为什么所有的DateTimes总是{01.01.0001 00:00:00}?
When I create the first time a issue entity I add the DateTimme in the SaveChanges() Method with the following modification in my DBContext:当我第一次创建问题实体时,我在 SaveChanges() 方法中添加了 DateTimeme,并在我的 DBContext 中进行了以下修改:
public override int SaveChanges()
{
var entries = ChangeTracker
.Entries()
.Where(e => e.Entity is BaseEntity && (
e.State == EntityState.Added
|| e.State == EntityState.Modified));
foreach (var entityEntry in entries)
{
((BaseEntity)entityEntry.Entity).UpdatedDate = DateTime.UtcNow;
if (entityEntry.State == EntityState.Added)
{
((BaseEntity)entityEntry.Entity).CreatedDate = DateTime.UtcNow;
}
}
return base.SaveChanges();
}
And the SaveChanges() works without problem. SaveChanges() 可以正常工作。 When I create the issue entity the first time the DateTime has the correct value and I can also see it in the Detail View.
当我第一次创建问题实体时,DateTime 具有正确的值,我也可以在详细信息视图中看到它。
Change your edit code to this将您的编辑代码更改为此
var exist = d.Set<Issue>().FindAsync(issue.Id);
if (exist == null)
{
//ErrorMessage = "Can't find item to update";
}
else{
db.Entry(exist).CurrentValues.SetValues(issue);
var result = await db.SaveChanges(); // result should be > 0
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.