3

我的 Grails 代码有一个搜索功能,它在执行 findAllBy 查询后重定向到另一个控制器操作:

def results = Foo.findAllByBar(baz)
redirect(action: "result", params: [results: results])

如预期的那样,findAllByBar 返回一个带有模型的 ArrayList,但在重定向之后,接收操作会获得一个字符串数组。更糟糕的是,当只有一个结果时,它甚至没有得到一个数组,它只是得到一个字符串。

鉴于我必须遍历接收视图中的结果,因此在字符串上执行此操作将仔细地单独打印每个字母。我们都同意这可能不是理想的行为。

4

2 回答 2

8

重定向会导致带有查询字符串中参数的新 GET 请求,例如 /controller/result?foo=bar&baz=123 - 您不能将对象放在那里,因为它只是一个字符串。

您可以将对象的 id 放在参数中并将它们加载到result操作中:

def action1 = {
   def results = Foo.findAllByBar(baz)
   redirect(action: "result", params: [resultIds: results.id.join(',')])
}

def result = {
   def resultIds = params.resultIds.split(',')*.toLong()
   def results = Foo.getAll(resultIds)
}

或将它们放在 Flash 范围内:

def action1 = {
   flash.results = Foo.findAllByBar(baz)
   redirect(action: "result")
}

def result = {
   def results = flash.results
}
于 2011-08-27T15:02:13.487 回答
2

听起来您想使用链方法而不是重定向方法。Chain 允许您将模型作为类似于渲染的参数传递。一个例子是:

chain(action:'result',model:[results:results])

下面是更多信息的链接:http: //www.grails.org/doc/latest/ref/Controllers/chain.html

于 2011-09-13T18:08:39.020 回答