2015-09-01 138 views
0

我有這個卡車維修計劃系統,現在這是我的更新卡車詳細控制器,在更新此我還必須更新卡車的當前運行,並且卡車當前運行將轉到最後一次運行?我很難弄明白。這是我的代碼:MVC更新詳細信息控制器

public ActionResult UpdateTruck(TruckDetails u, int id) 
    { 

     var updateTruck = db.trucks.FirstOrDefault(s => s.id == id); 

     if (updateTruck == null) 
      return View(u); 

     var lastrun = db.trucks.Select(s => s.current_run); // This is my problem, getting the current run value from the database 

     updateTruck.registration_no = u.reg_no; 
     updateTruck.make = u.make; 
     updateTruck.model = u.model; 
     updateTruck.engine_no = u.engine_no; 
     updateTruck.chassis_no = u.chassis_no; 
     updateTruck.driver_name = u.driver_name; 
     updateTruck.driver_no = u.driver_no; 
     updateTruck.is_updated = DateTime.Now; 
     updateTruck.current_run = u.current_run; 
     updateTruck.last_run = lastrun; 

     if (ModelState.IsValid) 
     { 
      db.SaveChanges(); 
      return View(u); 
     } 

     return View(u); 


    } 

預先感謝您

+1

我不知道您在找什麼建議 – Jonesopolis

回答

1

只需設置LASTRUN = updateTruck.current_run從數據庫

public ActionResult UpdateTruck(TruckDetails u, int id) { 

    var updateTruck = db.trucks.FirstOrDefault(s => s.id == id); 

    if (updateTruck == null) 
     return View(u); 

    var lastrun = updateTruck.current_run; 

    updateTruck.registration_no = u.reg_no; 
    updateTruck.make = u.make; 
    updateTruck.model = u.model; 
    updateTruck.engine_no = u.engine_no; 
    updateTruck.chassis_no = u.chassis_no; 
    updateTruck.driver_name = u.driver_name; 
    updateTruck.driver_no = u.driver_no; 
    updateTruck.is_updated = DateTime.Now; 
    updateTruck.current_run = u.current_run; 
    updateTruck.last_run = lastrun; 

    if (ModelState.IsValid) 
    { 
     db.SaveChanges(); 
     return View(u); 
    } 

    return View(u); 


} 

FWIW我可能會得到乾淨的實體時,一點點的代碼。您在操作中接受的參數爲int id,但如果出現問題,則不會將其傳回給視圖,因此我假設該ID應該位於您的TruckDetails模型上,因此您應該使用該參數,或者將其添加到該參數中。如果您的ModelState無效,您還想跳過所有其他代碼

public ActionResult UpdateTruck(TruckDetails u) 
    { 
     if (u != null && ModelState.IsValid) 
     { 
      var updateTruck = db.trucks.FirstOrDefault(s => s.id == u.id); 
      if (updateTruck != null) 
      { 
       var lastrun = updateTruck.current_run; 
       updateTruck.registration_no = u.reg_no; 
       updateTruck.make = u.make; 
       updateTruck.model = u.model; 
       updateTruck.engine_no = u.engine_no; 
       updateTruck.chassis_no = u.chassis_no; 
       updateTruck.driver_name = u.driver_name; 
       updateTruck.driver_no = u.driver_no; 
       updateTruck.is_updated = DateTime.Now; 
       updateTruck.current_run = u.current_run; 
       updateTruck.last_run = lastrun; 
       db.SaveChanges(); 
      } 
     } 
     return View(u); 
    } 
+0

非常感謝您!很抱歉我是一個新手,很少和明顯的錯誤 –