如何在 play 框架中以 scala 形式使用 POST 方法?

How to use POST method in scala form in play framework?

我正在尝试提交一个将重定向到另一个 HTML 页面的表单。但是action方法不行。

view.html

@(bookForm:Form[Book])(implicit messages: Messages)
<html>
<head>
    <title>Create Books</title>
<body>
<h1>Create Books</h1>
@helper.form(action=routes.BooksController.save()){
    @helper.inputText(bookForm("id"))
    @helper.inputText(bookForm("title"))
    @helper.inputText(bookForm("price"))
    @helper.inputText(bookForm("author"))
}
<input type="submit" value="Create Book" />
</body>
</head>
</html>

controller.scala

  def index() = Action {
    val books = Book.allBooks()
    Ok(views.html.books.index(books))
  }
  def create() = 
      Action { implicit request =>
      Ok(views.html.books.create(Book.bookForm))
  }
  def save() =
      Action { implicit request =>
      val book = Book.bookForm.bindFromRequest().get
      Book.add(book)
      Redirect(routes.BooksController.index())

定义的路线是

GET    /books              controllers.BooksController.index()
GET    /books/create       controllers.BooksController.create()
POST   /books/create       controllers.BooksController.save()

您的提交按钮应该在表单标签内:

@helper.form(action=routes.BooksController.save()){
    @helper.inputText(bookForm("id"))
    @helper.inputText(bookForm("title"))
    @helper.inputText(bookForm("price"))
    @helper.inputText(bookForm("author"))
    <input type="submit" value="Create Book" />
}