如何在Play框架中以Scala形式使用POST方法?

时间:2019-04-10 13:31:03

标签: scala playframework

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

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()

1 个答案:

答案 0 :(得分:0)

您的提交按钮应位于表单标签内

@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" />
}