Reputation: 45
How can I automatically add a date to my database in MVC? I don't know how to get the time from my computer without manually writing it in line c.Date = ;
. My controller:
public ActionResult Add(Contact c)
{
bool Status = false;
string message = "";
if (ModelState.IsValid)
{
c.Date = DateTime;
db.Contact.Add(c);
db.SaveChanges();
Status = true;
}
else
{
message = "Invalid Request";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(c);
}
Upvotes: 0
Views: 119
Reputation: 2354
You need to use the DateTime.Now
property, also don't forget you can easily format the DateTime.Now
with additional functions like DateTime.Now.ToLongDateString()
.
I've added it in your code:
public ActionResult Add(Contact c)
{
bool Status = false;
string message = "";
if (ModelState.IsValid)
{
c.Date = DateTime.Now;
db.Contact.Add(c);
db.SaveChanges();
Status = true;
}
else
{
message = "Invalid Request";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(c);
}
Upvotes: 0
Reputation: 36
Just simply use DateTime class.
c.Date = DateTime.Now;
Regarding the format, you can check this site: C# DateTime Format
Upvotes: 2