播放框架2:如何在路线,视图和控制器之间传递对象? [英] Play framework 2 : How to pass object between routes, views, and controller?

查看:128
本文介绍了播放框架2:如何在路线,视图和控制器之间传递对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将书对象从视图传递到路线,然后将其发送到控制器中进行计算.我的代码如下:

I'm trying to pass a book object from views to routes, and then send it to calculate in a controller. My code is following:

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>

}

路线

...
GET     /order                      controllers.Application.buy(book: models.Book)
...

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

However, It gave me an error : No QueryString binder found for type models.Book. Try to implement an implicit QueryStringBindable for this type.

我试图将路线更改为:

    GET     /order                      controllers.Application.buy(book)

它还返回了一个错误:

type mismatch; found : String required: models.Book

推荐答案

这不是Play路由的工作方式. Play路由器会解析URL或查询字符串中的变量,然后通过QueryBindable类型类将其转换为本机类型.您应该有更多类似这样的东西:

That's not how Play routing works. The Play router parses variables from the URL or query string, and converts them to native types via the QueryBindable typeclass. You should have something more like this:

路线

GET /order/:bookid           controllers.Application.buy(bookid: String)

动作应为:

Application.scala

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

还有这样的模板:

bookList.scala.html

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

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

Of course if your model's ID is other than String you need to modify the route's param type

更新-使用表单/POST的替代方法

使用POST方法的表单是一种更好的解决方案,或者用户每次单击URL时都会购买另一本书,并且ID会暴露出来.查看表单文档.您的模板将如下所示:

A form with a POST method is a better solution, or the user will buy another book each time they click the URL, and the id will be exposed. Check out the forms documentation. Your template would be like this:

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

这篇关于播放框架2:如何在路线,视图和控制器之间传递对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆