【问题标题】:Grails controller not passing errors to the gsp pageGrails 控制器没有将错误传递给 gsp 页面
【发布时间】:2012-05-31 08:35:25
【问题描述】:

不确定我在这里做错了什么。我希望它是微妙的。我似乎无法将错误传递给我的 gsp 页面。我的控制器中有以下代码:

def submit = {
    if (params) { // if there are parameters
        def sampleInstance = new Sample(params)// new sample
        if (sample.validate()) { // try to validate
            sample.save()
            flash.message = "Successfully Entered Sample"
            redirect ( action: 'sample' )
        }else{
            flash.message = "Error Entering Sample"
            sampleInstance.errors.each {
                println it
            }
            redirect ( action: 'sample', model:[sampleInstance:sampleInstance])
        }
    } 
}

我已验证 params 不为空。验证失败会创建 hasErrors() ,它也已经过验证,并且代码 sample.errors.each {println it} 会通知我正确的字段错误,正如我所期望的那样。但是我的重定向语法可能有问题?因为flash.message 可以工作,但我无法访问model:[sampleInstance:sampleInstance] 地图并且不会呈现错误。

这是我的 gsp 中的代码:

     <g:hasErrors>
        <div class="errors">
         <g:renderErrors bean="${sampleInstance}" as="list" />
        </div>

     </g:hasErrors>

我的控制器叫SubmitSampleController,动作叫submit,gsp页面叫sample.gsp。

这可能是我的问题的答案:我有另一个名为 sample 的操作,也许我需要在 sample 操作中执行我的所有逻辑,而不是在提交操作中?或者有没有办法将模型从一个动作传递到同一个控制器内的另一个动作?我有一种感觉,我的原始模型正在丢失。

def sample(){
    def now = new Date()// today's date
    def today = com.Sample.findAllBySampleReceivedDateGreaterThanEquals(now.clearTime())// finds all samples submitted today
   [checkDate:today, date: now] // passes a map of checkDate and todays date to the sample.gsp page
}

【问题讨论】:

    标签: grails groovy


    【解决方案1】:

    在重定向中,模型用作查询参数,这与渲染不同,渲染执行实际转发并将对象置于请求范围内。如果出现错误,您需要做的是 渲染 视图并传递模型。然后你会得到想要的输出。

    【讨论】:

    • 感谢工作。我最终将我的两个操作合并为一个以简化事情,但很高兴知道我可以为同一个 gsp 页面使用多个操作。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 2015-07-07
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多