1

我正在尝试将一些数据绑定到作为命令对象一部分的对象。该对象在尝试使用它时保持为空。可能我没有在 gsp 中提供正确的数据,但我不知道我做错了什么!

我希望当我提交一个字段名称为“book.title”的表单时,它会被映射到命令对象中……但这失败了……标题保持 [null]

每当我更改命令对象和表单以使用字符串标题作为属性时,它都会起作用..

// the form that submits the data
<g:form>
   <g:textField name="book.title" value="Lord Of the Rings"/><br>
   <br><br>
   <g:actionSubmit action="create" value="Create!"/>
</g:form>


// the controller code
def create = { BooksBindingCommand cmd ->
   println cmd?.book?.title // the book property always stays null
   redirect(action: "index")
}

// the command object
class BooksBindingCommand {
   Book book
}

// the book class, simple plain groovy class
class Book {
   String title
}

关于为什么'book.title'的绑定失败的任何建议?

4

2 回答 2

7

尝试在绑定之前对其进行初始化,例如:

// the command object
class BooksBindingCommand {
   Book book = new Book()
}
于 2012-01-26T01:30:15.820 回答
0

只是快速刺一下。

表单字段名称可能应该是 book_title 而不是使用句点(不确定在控制器中处理时是否会成为问题)。

<g:textField name="book_title" value="Lord Of the Rings"/><br>

在您的控制器中,首先创建您的图书模型,然后将其分配给您希望它绑定到的类。

def create = {
  def mybook = new Book()
  mybook.title = params.book_title
  def binder = new BooksBindingCommand()
  binder.book = mybook
}

BooksBindingCommand 是模型吗?因为我不确定你想要达到什么目的。

于 2012-01-25T23:49:45.237 回答