iT邦幫忙

0

GetById這方法若取到的ID裡面內容是NULL

  • 分享至 

  • xImage
[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去資料庫撈資料確認資料庫是否有資料

  1. 有資料,要把使用者新資料更新後儲存
  2. 沒資料,不做任何事情
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1

我應該會這樣做....
else沒有東西就不用寫
不需要儲存就return

        trainingTextToEdit = trainingTextService.GetById(id, true);

        if (trainingTextToEdit == null)
        {
            trainingTextToEdit = new TrainingText();
            //可以放ViewBag之類的給前端知道,這個編輯有問題,找不到資料等訊息
            return View(trainingTextToEdit);
        }       

我要發表回答

立即登入回答