I want to fill the form according to the related book when I click the view or update the link on the page. I know, there is a solution with opening another page but I want to do it on the same page. As you can see on the picture below I can properly get the list on the left table. I have tried a post method below but did not work. So what would you recommend to do it?
Controller class:
@PostMapping(path = "/listbooks")
public String getBook(@ModelAttribute BookConfig bookConfig, Model model)
throws IOException {
model.addAttribute("book", bookConfig);
return "list";
}
@GetMapping(path = "/listbooks")
public String showAllBooks(Model model) throws IOException {
model.addAttribute("books", bookService.getBookConfigList());
return "list";
}
HTML file:
<div class="table-responsive" th:if="${not #lists.isEmpty(books)}">
<table class="table table-hover" style="height:50px;">
<thead class="thead-inverse">
<tr>
<th>Name</th>
<th>View</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tr th:each="book : ${books}">
<td th:text="${book.name}">Book Name</td>
<td><a href="#" th:href="@{'/books/listbooks/'}">View</a></td>
<td><a href="#" th:href="@{'/books/listbooks/'}">Update</a></td>
<td><a href="#" th:href="@{''}">Delete</a></td>
</tr>
</table>
</div>
This is what I am trying to do on the HTML file:
<form th:if="${book != null}" th:object="${book}" th:action="@{/book/}"
method="post">
<div class="panel-heading">
<h4 class="panel-title"
">Edit
Book Configuration</h4>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3 form-group"
>
<label>Book name</label>
<input type="text" class="form-control" th:field="*{name}"/>
</div>
...
I have solved using JavaScript, Firstly, I have adjusted the getBook method below
@PostMapping("/books")
public String getBook(@RequestBody String bookName) throws IOException {
return "list";
}
and then I have add these two JS functions:
$(document).ready(function () {
$(".view").click(function () {
var $row = $(this).closest("tr"); // Find the row
var $text = $row.find(".bookname").text(); // get the text on the view link using its the class name
$.post("http://localhost:8081/books",
{
bookName: $text
},
function (data, status) {
assignDataToTable(data);
});
});
});
function assignDataToTable(data) {
alert("hey" + data);
document.getElementById("booknameinput").value = data;
}
question from:
https://stackoverflow.com/questions/65874879/spring-mvc-fill-model-on-the-form 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…