【问题标题】:How redirect to action of different controller with parameters of the target controller in grails如何使用grails中目标控制器的参数重定向到不同控制器的动作
【发布时间】:2016-12-27 05:41:46
【问题描述】:

我有两个域类 Author 和 Book 相关为一对多。当我为特定作者创建一本新书时,我想(在单击保存按钮后)重定向到作者控制器的显示操作,以便显示特定作者的完整详细信息以及他创作的所有书籍的列表。

class Author {
  String fistName
  String secondName

  static hasMany = [books: Book]
}

class Book {
  String title
  String dateOfPublication
  //Author author

  static belongsTo = [author: Author]
}


//BookController
def save() {
    def bookInstance = new Book(params)
    if (!bookInstance.save(flush: true)) {
        render(view: "create", model: [bookInstance: bookInstance])
        return
    }

    flash.message = message(code: 'default.created.message', args: [
      message(code: 'book.label', default: 'Book'),
      bookInstance.id])

    if(params.tempid){
      redirect(action: "show", controller: "author", id: params.id)
    }else{
      redirect(action: "show", id: params.tempid)
    }
}

但是,上面的代码并没有按照我的意愿重定向我,而是执行了 else 语句,并显示了 flash 消息“未找到 ID 为 null 的书”

下面是在 Author 类的 show.gsp 中渲染的 _book.gsp 模板。

 <table class="table table-striped table-hover" id="book-data">
        <thead>
          <th class="sortable">Title</th>
          <th class="sortable">Date of Publication</th>
        </thead>

        <tbody>
          <g:each in="${authorInstance.book}" status="i" var="p">
            <tr class="prop">
              <td style="vertical-align: middle;" valign="top" class="value">${p?.title}</td>
              <td style="vertical-align: middle;" valign="top" class="value">${p?.dateOfPublication}</td>
             <td style="vertical-align: middle;" valign="top"><g:link class="btn btn-edit" action="edit" controller="book" id="${p?.id}"> Edit</g:link></td>
            </tr>
          </g:each>
        </tbody>
      </table>

我怎样才能做到这一点。?

感谢您的帮助。

已编辑:authorInstance.id 更改为 params.id

【问题讨论】:

  • 您在重定向中使用了id: authorInstance.id,但您的代码中没有定义authorInstance
  • 我将 authorInstance.id 更改为 params.id 我认为这应该可以工作,但它仍然会产生这条 flash 消息“找不到 ID 为 null 的书”,这是 else 语句的结果。如何访问正确的作者实例?
  • if(params.tempid){ redirect(action: "show", controller: "author", id: params.id) }else{ redirect(action: "show", id: params.tempid) } - 这对我来说看起来很奇怪。如果 tempid 为 null 或为空,您是否使用此值进行重定向?你对这里有什么期望?什么是脾气暴躁?

标签: grails


【解决方案1】:

如果您想在保存book 后重定向到您的作者实例,您应该在保存请求参数中发送作者的id。默认情况下,作者 ID 包含在 params 映射中,为 author.id。 所以这应该可以工作:
redirect(action: "show", controller: "author", id: params.author.id)

【讨论】:

  • 是的,它有效,但我必须摆脱 if 语句中的 tempid 并将其替换为 params.author.id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多