【问题标题】:Populating View fields from Controller in Grails在 Grails 中从 Controller 填充视图字段
【发布时间】:2011-11-16 23:17:40
【问题描述】:

我正在尝试通过控制器上的操作将值加载到视图上的字段中。如何引用我要加载的特定字段?在 .NET 中,它类似于:在按钮单击事件中,this.txtName.Text = "John"。我不明白如何从控制器中做到这一点,特别是如何引用视图字段。我曾尝试使用 params 对象,但它即将为空。我知道我正在根据我使用的 println 语句执行操作。

这里是相关代码sn-ps:

从视图:

<td valign="top" class="value ${hasErrors(bean: planetInstance, field: 'name', 'errors')}">
  <g:textField name="name" value="${planetInstance?.name}"/>
</td>
<td class="load">
  <g:actionSubmit value="Load" action="nameLoad"/>
</td>

来自控制器:

def nameLoad = {
    // I want to reference and load the "name" textField from the view
}

任何帮助将不胜感激。

【问题讨论】:

  • 我建议您使用grails generate-all 为您的域类之一生成一些 CRUD 页面。查看生成的代码以了解应该如何完成

标签: grails views controllers


【解决方案1】:

我无法从您的代码中看出,但您可能忘记在控制器操作 nameLoad 中映射变量 name:

class YourController{    
    def nameLoad = {
        def name = Planet.get(params.id).name //This can be whatever you need it to be to get the correct value assigned to the "name" variable.  Here I assume you have a domain class called "Planet" which may or may not be the case.
        return [name:name] //This is where you map key/value pairs.  The name of the key is what you will type to access the value in your view.  The value is the name of the variable you are dealing with, in this case "name".
    }
}

按照上面代码的设置方式,Grails 将假定文件夹YourController 中有一个名为nameLoad 的视图。所以 URL 将类似于:

http://localhost:8080/yourapp/yourcontroller/nameload

在该视图中,您将像这样访问name:

${name}

可以在任意数量的标签中使用,例如&lt;g:select&gt; 标签:

<g:select from="${name}" />

【讨论】:

  • 当我尝试您上面提到的代码时,我在 def name... 行收到错误消息:java.lang.NullPointerException: Cannot get property 'name' on null object at grailstagstest。 PlanetController$_closure9.doCall(PlanetController.groovy:103)
  • 我终于在控制器上的 nameLoad 操作中使用以下代码让它工作: def planetInstance = new Planet() planetInstance.properties = params planetInstance.name = "Jupiter" render(view: "创建”,模型:[planetInstance:planetInstance])
  • 我没有在给您的代码中创建任何内容,因为您的操作名称是 nameLoad 而不是 create,但概念是相同的。正如我在发布的代码的第一条评论中指出的那样,您必须使用任何合适的代码(在您的情况下,我猜创建一个新行星是合适的)填充有问题的变量,然后映射该变量。像您一样使用render 允许您使用名称与控制器操作不同的视图,就像我向您展示的方式假定存在与您的控制器操作同名的视图(我在回答中指出)。
【解决方案2】:

您应该能够使用params.name 访问文本字段的值。如果这不起作用,您的视图可能有问题。 g:textField 和 g:actionSubmit 标签是否包含在 form 或 g:form 中?

【讨论】:

  • 是的,我在 g:form 标签内有 g:textField 和 g:actionSubmit 标签。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多