如何初始化DateTime属性以显示Date.Now



我试图设置DateTime字段显示当前时间和日期。

public DateTime Date { get; set;  }

我到目前为止尝试传递setterDate.Now但不工作。我问是因为我需要显示DateTime。现在在视图中,但这个项目应该对User隐藏。用户只能看到DateTime,不能看到Edit。同样在Controller中,我使用了but doesn't work

DateTime Date = DateTime.Now;

知道我在哪里犯了错误,如何解决这个问题吗?

这是我的控制器

public NotesController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<Notes> notes = _db.Notes.Include(u => u.Patient);
return View(notes);
}
//Upsert GET
public IActionResult Upsert(int? Id)
{
DateTime Date = DateTime.Now;

NotesVM notesVM = new NotesVM()
{
Notes = new Notes(),
PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
})
};

Notes notes = new Notes();
if (Id == null)
{
// this is for create
return View(notesVM);
}
else
{
// this is for edit
notesVM.Notes = _db.Notes.Find(Id);
if (notesVM.Notes == null)
{
return NotFound();
}
return View(notesVM);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upsert(NotesVM notesVM)
{
if (ModelState.IsValid)
{
if (notesVM.Notes.Id == 0)
{
//Creating
_db.Notes.Add(notesVM.Notes);
}
else
{
//Updating
_db.Notes.Update(notesVM.Notes);
}
_db.SaveChanges();
return RedirectToAction("Index");
}
notesVM.PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
});
return View(notesVM);
}

如果你有一个控制器的构造函数,你可以这样设置date属性:

public NotesController(ApplicationDbContext db)
{
_db = db;
Date = DateTime.Now;
}

更新了我的答案,现在我已经看到了你的构造函数。

最新更新