【问题标题】:Attempting to add a "delete" button to existing "details" view尝试向现有的“详细信息”视图添加“删除”按钮
【发布时间】:2022-02-08 20:15:17
【问题描述】:

我正在开发一个允许用户创建、存储、编辑和删除笔记的小组项目。

我们能够通过一个非常基本的“详细信息”视图访问存储的笔记,并希望在该详细信息视图中提供“删除”功能,而无需创建单独的“删除”视图。

到目前为止,这就是我们的“详细信息”处理程序在控制器中的外观:

    public String displayNoteDetails(Model model, @RequestParam int id, @RequestParam int userId) {

        Optional<SecretNote> result = noteRepository.findById(id);

        if (result.isEmpty()) {
            model.addAttribute("title", "Invalid Note ID: " + id);
            return "redirect:../";
        } else {
            SecretNote secretNote = result.get();
            model.addAttribute("title", secretNote.getName() + " Details");
            model.addAttribute("secretNote", secretNote);
        }
        return "notes/details";
    }
}

我能够在“详细信息”视图中显示一个“删除”按钮,其中包含以下内容:

<form th:action="delete" method="post" th:object="${secretNote}">
        <input type="hidden" th:field="${secretNote.id}"/>
        <button type="submit" value="Submit" class="btn btn-danger">Delete</button>
</form>

但是,当单击“删除”按钮时,它会重定向到http://localhost:8080/notes/delete,大概是因为我设置了“删除”按钮。我想向displayNoteDetails 添加代码,让我可以使用noteRepository.deleteById(id);,然后重定向到"notes/index"(显示所有注释的用户主页)。

FWIW,以下是我们在计划单独视图时使用删除处理程序的方式:

@GetMapping("delete")
    public String displayDeleteNoteForm(@RequestParam int id, @RequestParam int userId) {
        noteRepository.deleteById(id);
        return "notes/index";
    }

    @PostMapping("delete")
    public String processDeleteNoteForm(Model model, @RequestParam(required = false) int[] noteIds) {

        if (noteIds !=null) {
            for (int id : noteIds) {
                noteRepository.deleteById(id);
                model.addAttribute("delete");
            }
        }
        return "notes/index";

    }

提前对格式化表示歉意。我显然是个新手。

【问题讨论】:

    标签: java html spring-boot thymeleaf crud


    【解决方案1】:

    替换:

    <form th:action="delete" method="post" th:object="${secretNote}">
    

    与:

    <form th:action="@{/notes/{id}/delete(id=${secretNote.id})}" method="post" th:object="${secretNote}">
    

    这将在表单的操作 URL 中添加注释的 id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-05
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 2017-07-02
      • 1970-01-01
      相关资源
      最近更新 更多