This will be a simple one for someone. I am just learning the MVC way.
I have a user provide me with a start time (start) and a duration (LengthOfShift) for a work period in view.
I want to store the start time, the duration and then a calculated finish time in the database.
I think I understand that the model is the best place to undertake the calculation and it is not best practice to do the calculations in the controller or view.
My simplified Model and controller are below. This doesn't seem though seem to work.
Any pointers as to what I am doing incorrectly?
Model
public class Shift
{
public int ShiftId { get; set; }
public string Code { get; set; }
public DateTime Start { get; set; }
public TimeSpan LengthOfShift { get; set; }
public DateTime Finish
{
get {
return Start.Add(LengthOfShift);
}
}
}
Controller
public class ShiftsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Shifts
public ActionResult Index()
{
return View(db.Shifts.ToList());
}
// GET: Shifts/Create
public ActionResult Create()
{
return View();
}
// POST: Shifts/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ShiftId,Code,Start,LengthOfShift")] Shift shift)
{
if (ModelState.IsValid)
{
db.Shifts.Add(shift);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(shift);
}
}