将html表单动作绑定到需要一些参数的控制器方法 [英] Binding an html form action to a controller method that takes some parameters

查看:59
本文介绍了将html表单动作绑定到需要一些参数的控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Find控制器中,我有一个类似的方法:

public Result findLatest(String repoStr) {
    ............
}

通过一条路线链接的人:

GET     /latest                     controllers.Find.findLatest(repo: String)

然后,我在如下视图中有一个表单:

<form action="@routes.Find.findLatest()" method="get">
    ....
    <select name="repo">....</select>
</form>

但是显然那是失败的,因为它期望我在操作中无法满足的某些参数.这样做的正确方法是什么,而不必最终使findLatest方法在我的控制器中不带任何参数?

解决方案

建议提出了一些与我认为的最佳解决方案相近的建议(因为Play 2.1中的默认活页夹已不再支持F.Option).

我最终离开了这样的路线:

GET     /latest                     controllers.Find.findLatest(repo=null)

和类似的视图:

<form action="@routes.Find.findLatest(null)" method="get">
    <select name="repo"> .... </select>
....
</form>

并在控制器中:

public Result findLatest(String repoStr) {
    if(repoStr==null) {
        repoStr=Form.form().bindFromRequest().get("repo");
.....

这使我拥有第二条路线,例如:

GET     /latest/:repo                     controllers.Find.findLatest(repo: String)

In my Find controller I have a method like:

public Result findLatest(String repoStr) {
    ............
}

Which is linked through a route:

GET     /latest                     controllers.Find.findLatest(repo: String)

Then, I have a form in a view like:

<form action="@routes.Find.findLatest()" method="get">
    ....
    <select name="repo">....</select>
</form>

But obviously that is failing, because it is expecting some parameters that I do not fulfill in the action. What is the correct way to do this without having to end up leaving the findLatest method taking no parameters in my controller?

解决方案

Cavice suggested something close to what I consider the best solution for this (since F.Option are not supported anymore with the default binders in Play 2.1 ).

I ended up leaving the route like:

GET     /latest                     controllers.Find.findLatest(repo=null)

and the view like:

<form action="@routes.Find.findLatest(null)" method="get">
    <select name="repo"> .... </select>
....
</form>

and in the controller:

public Result findLatest(String repoStr) {
    if(repoStr==null) {
        repoStr=Form.form().bindFromRequest().get("repo");
.....

This allows me to have a second route like:

GET     /latest/:repo                     controllers.Find.findLatest(repo: String)

这篇关于将html表单动作绑定到需要一些参数的控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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