[HttpGet]
public IActionResult Edit(int id)
{
TrainingText? trainingTextToEdit = null;
if (id > 0)
trainingTextToEdit = trainingTextService.GetById(id);
if (trainingTextToEdit == null)
trainingTextToEdit = new TrainingText();
return View(trainingTextToEdit);
}
[HttpPost]
public IActionResult Edit(int id, string textType, string content, string creator)
{
TrainingText? trainingTextToEdit;
if (id == 0)
{
trainingTextToEdit = new TrainingText
{
createDate = DateTime.Now,
enterpriseId = 1,
departmentId = 1,
creator = "admin",
modifyDate = null,
modifier = "admin",
removed = false
};
}
else
{
trainingTextToEdit = trainingTextService.GetById(id, true);
if (trainingTextToEdit == null)
{
trainingTextToEdit = new TrainingText();
}
else
{
}
trainingTextToEdit.modifyDate = DateTime.Now;
}
trainingTextToEdit.textType = textType;
trainingTextToEdit.content = content;
trainingTextToEdit.creator = creator;
trainingTextService.Save(trainingTextToEdit);
return View(trainingTextToEdit);
}
在[HttpPost]的else裡面寫了
if (trainingTextToEdit == null)
{
trainingTextToEdit = new TrainingText();
}
這一段若取到的ID但裡面內容是NULL就給他new一個空的TrainingText(),但這個空的TrainingText(),並不需要儲存,在else裡面如果不寫東西是不是就不會儲存了?就等於不做任何事?這樣寫又感覺多了那個else
id是0的時候是屬於新增,要把使用者新資料更新後儲存
id不是0的時候是修改,先用id去資料庫撈資料確認資料庫是否有資料
我應該會這樣做....
else沒有東西就不用寫
不需要儲存就return
trainingTextToEdit = trainingTextService.GetById(id, true);
if (trainingTextToEdit == null)
{
trainingTextToEdit = new TrainingText();
//可以放ViewBag之類的給前端知道,這個編輯有問題,找不到資料等訊息
return View(trainingTextToEdit);
}