0

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);
    }
 }
cramar
  • 124
  • 1
  • 16
  • it is not storing the finish time. – cramar Jun 09 '15 at 10:48
  • Make it a property with a getter and setter - `public DateTime Finish { get; set; }` and in the controller set the value based on the `Start` and `LengthOfShift` properties. (but you should only be storing `Start` and `LengthOfShift` **OR** `Start` and `Finish` in your database anyway –  Jun 09 '15 at 10:52
  • This may help:http://stackoverflow.com/questions/4415904/business-logic-in-mvc – NoChance Jun 09 '15 at 10:59

2 Answers2

0

Try adding an empty setter to your calculated field

Matt Whetton
  • 6,616
  • 5
  • 36
  • 57
0

In the Create method, the Finish property is not included in binding. Include this property in binding and it should work. Hope that helps.

Just to add its done right using the getter property for Finish. Additional code for calculating the value that can be easily derived from the existing properties should not be required.

Yogi
  • 9,174
  • 2
  • 46
  • 61