I am building a little CRUD application in ASP.NET MVC5. Instead of a own model I am using the autogenerated models of EF. The table (named "tablex") accessed by EF has a DateTime value (named "inserted").
Controller:
// Show edit
public async Task<ActionResult> Edit(int? id)
{
tablex x = await db.tablex.FindAsync(id);
return View(x);
}
// Edit
public async Task<ActionResult> Edit([Bind(Include = "id,...,updated")] tablex x)
{
if (ModelState.IsValid)
{
x.inserted = DateTime.Now;
db.Entry(x).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(x);
}
This is my shortened Controller. As you can see I override my DateTime field anyway.
View:
@model DatabaseEF.Models.tablex
@using (Html.BeginForm())
{
<div....> //more fields
<div ...>
@Html.Label("Inserted ", ...)
<div ...>
@Html.EditorFor(model => model.inserted, ...)
@Html.ValidationMessageFor(model => model.inserted, "", ...)
</div>
<input type="submit" value="Save" ... />
</div>
}
With this my EditorFor-Textbox shows the date like "28.05.2015 17:12:17" (German format). When pressing "Save" the view warns that the field mus be a date. Changing the value to e.g. "2010-10-10" works perfectly.
Now I found some solutions with annotations to the model "DataType(DataType.Date)]". But as my model is autogenerated by the EF I'm looking for a working solution.
Anybody with help for me out there?