grailscommand-objects

Grails 2.5.0 - Command Object handle POST request with JSON


I have a form set up to send a POST request to a Grails controller, which is using a Command Object as its one parameter. The Command Object contains some properties binding correctly along with a List of items, which is not binding correctly. What I'm doing is sending the other parameters normally via the POST request but wrapping the list up as a JSON string, as I'm not sure of another way to send a list via POST (aside from, say, an XML string). What's the final step in getting the command object to bind the list properly from the string, or is there a better way to send the list to the command object?

Edit: Here is a simplified version:

Testing the URI:

request.forwardURI = 'list1=[{"listprop1":"a","listprop2":"b"}]&prop1=c&prop2=d'

The command objects:

class MyListCommand {
    String listprop1
    String listprop2

    static constraints = {
        listprop1 nullable: true
        listprop2 nullable: true
    }
}

class MyCommand {
    List<MyListCommand> list1 = [].withLazyDefault {
        new MyListCommand('[]')
    }
    String prop1
    String prop2

    static constraints = {
        prop1 nullable: true
        prop2 nullable: true
    }
}

The form:

<form action="${createLink(action: 'myAction')}" method="post">
                <div ng-repeat="list1 in list1array">
                    <input type="hidden" name="list1[{{ $index }}].listprop1" value="{{list1.listprop1}}"/>
                    <input type="hidden" name="list1[{{ $index }}].listprop2" value="{{list1.listprop2}}"/>
                </div>
                <input name="prop1" type="text">
                <input name="prop2" type="text">
            </form>

Solution

  • Try sending the request like this:

    request.forwardURI = 'list1[0].listprop1=a&list1[0].listprop2=b&prop1=c&prop2=d'
    

    Even better

    A better approach is to use Ajax with the g:remoteForm tag.