Play 框架 如何将集合传递给动作 create()?
我是 Play 框架的初学者。我在传递参数时遇到问题。
我想将集合从视图传递到控制器。我不知道该怎么做。当我从视图中获取集合时,我总是得到“null”。 我的代码如下:
控制器中的代码:
public static void create(List<Book> books) throws Exception {
for(Book book : books){
System.out.println(book.get(0).author) // i got null :(
}
}
HTML 中的代码
Book 1:
<input type="text" name="books.author" />
<input type="text" name="books.title" />
Book 2:
<input type="text" name="books.author" />
<input type="text" name="books.title" />
当我提交时,我想向数据库添加 2 条记录,包括 Book1 和 Book2。请支持我
谢谢
I am starter with Play Framework. I got a problem when i passed parameters.
I want to pass a collection from view to controller. And i do not know how to do this. I always get "null" when i get a collection from view.
My code below:
Code in controller:
public static void create(List<Book> books) throws Exception {
for(Book book : books){
System.out.println(book.get(0).author) // i got null :(
}
}
Code in HTML
Book 1:
<input type="text" name="books.author" />
<input type="text" name="books.title" />
Book 2:
<input type="text" name="books.author" />
<input type="text" name="books.title" />
When i submit, i want to add 2 records into database include Book1 and Book2. Please support me
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需将数组指示符添加到您的 HTML 代码中即可完成这项工作。
我已经测试了这个解决方案,它工作得很好。
另请注意,您的 println 将无法编译,因为您在 Book 对象上调用
get(0)
,而不是 List 对象。如果您只是 printlnbook.author
,它会根据需要输出作者。You can make this work by simplying add the array indicator to your HTML code
I have tested this solution, and it works fine.
Also note that your println will not compile, as you are calling
get(0)
on the Book object, and not the List object. If you just printlnbook.author
, it outputs the author as required.如果有人需要动态添加和删除书籍的 Javascript 示例(需要 JQUERY):
In case anyone needs an example of the Javascript for dyanmically adding and removing books (JQUERY needed):