Play框架2:如何在路由,视图和控制器之间传递对象?

lva*_*yut 3 scala playframework-2.0

我正在尝试将一个book对象从视图传递到路由,然后将其发送到控制器中进行计算.我的代码如下:

bookList.scala.html

@(books: java.lang.Iterable[Book])

@main("BookList"){
    <div class="row">
        @for(book <- books.iterator()){
            <div class="col-sm-6 col-md-4">
                <div class="thumbnail" style="height: 435px">
                         ...
                        <p><a href="@routes.Application.buy(book)" class="btn btn-primary" role="button"
                              style="vertical-align:bottom">Order now!</a>
                    </div>
                </div>
            </div>
        }
    </div>

}
Run Code Online (Sandbox Code Playgroud)

路线

...
GET     /order                      controllers.Application.buy(book: models.Book)
...
Run Code Online (Sandbox Code Playgroud)

但是,它给了我一个错误: No QueryString binder found for type models.Book. Try to implement an implicit QueryStringBindable for this type.

我试图改变路线:

    GET     /order                      controllers.Application.buy(book)
Run Code Online (Sandbox Code Playgroud)

它还返回了一个错误:

type mismatch; found : String required: models.Book
Run Code Online (Sandbox Code Playgroud)

Ric*_*ose 9

这不是播放路由的工作原理.Play路由器解析URL或查询字符串中的变量,并通过QueryBindable类型类将它们转换为本机类型.你应该有更像这样的东西:

路线

GET /order/:bookid           controllers.Application.buy(bookid: String)
Run Code Online (Sandbox Code Playgroud)

行动应该是这样的:

Application.scala

def buy(bookid: String) = Action { request =>
    // Look up book by id here.
   Ok(views.html.thanks("you bought a book!"))
}
Run Code Online (Sandbox Code Playgroud)

这样的模板:

bookList.scala.html

@for(book <- books.iterator()) {
    ...
    <a href="@routes.Application.buy(book.id)" class="btn btn-primary"         
}
Run Code Online (Sandbox Code Playgroud)

当然,如果您的模型的ID不是String您需要修改路径的参数类型

更新 - 使用表单/ POST替代

使用POST方法的表单是更好的解决方案,或者用户每次单击URL时都会购买另一本书,并且ID将被公开.查看表单文档.你的模板是这样的:

@for(book <- books.iterator()) {
    ...
    <form method="post">
      <div>@book.name</div>
      <input type="hidden" value="@book.id"/><button type="submit">buy</button>
    </form>
}
Run Code Online (Sandbox Code Playgroud)