Question

im trying knockout doing a little test and i have not been able to do this very basic thing with knockout.. i want to return a list from my controller then take that list with my knockout viewmodel and finally bind it to a dropdown in my view.

i have this controller:

 @RequestMapping(value="/getUsers", method = RequestMethod.GET)
    public List<User> returnUsers(@ModelAttribute User user) {
       User user1=new User(), user2, user3 ;
       List<User>users=new ArrayList<User>();

        user1.setLastName("adsfa");
        user1.setName("adfds");
        user1.setAge(26);
        user2=new User();
        user2.setLastName("testLastName2");
        user2.setName("testName2");
        user2.setAge(45);
        user3=new User();
        user3.setLastName("testLastName2");
        user3.setName("testName3");
        user3.setAge(33);
        users.add(user1);
        users.add(user2);
        users.add(user3);

        return users;
    }

this is my knockout viewmodel:

function viewModel() {

    this.name = ko.observable("bob");
    this.lastName = ko.observable("smith");
    this.age = ko.observable(26);
    this.validationMessage = ko.observable();

    this.users = ko.observableArray([]);
    this.loadUsers(); //with this function call i want to initialize users with my controller data.

    }

    //this funcion should get the data from my controller
    viewModel.prototype.loadUsers = function() {
        var tmp = this.users();
        $.get("/vacation_booking/getUsers", function (data) {
            tmp(ko.toJS(data));
            log.info("Usuarios:" + data);

        });

    }


 /*
this.Age = ko.dependentObservable({
    read: this.age,
    write: function (value) {
        if (!isNaN(value)) {
            this.age(value);
           this.validationMessage("");
        }
        else {
            this.validationMessage("Age must be a number!");
        }

    },
    owner: viewModel
});
 */

 var save = function(){

   // var jsonData = ko.toJSON(viewModel);
   // alert("Could now send this to server: " + JSON.stringify(jsonData));
    $.ajax({
        url: "/vacation_booking/save",
        dataType: "json",
        type: "POST",
        data: "name=" + this.name() + "&lastName=" + this.lastName() + "&age=" + this.age(),
        success: function(data){
            alert("Successful");
        },
        failure: function(){
            alert("Unsuccessful");
        }
    });
  }




 ko.applyBindings(new viewModel());

this is my view:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>

 </head>

            <h1>Testing</h1>
            <p>
                <a href="${pageContext.request.contextPath}/specRunner" target=_blank>Launch Test Runner</a>
            </p>

            First Name: <input type="text" data-bind="
                                    value: name,
                                    valueUpdate : 'afterkeydown'
                                    "/>
            <br />

            Last Name: <input type="text" data-bind="value:lastName, valueUpdate : 'afterkeydown'" />

            <br />

            Age: <input type="text" data-bind="value: age, valueUpdate : 'afterkeydown'" />

            <Br />
            <!--p>Destination country: <select data-bind=" options : availableCountries"></select></p-->
            <Br />
            <span data-bind="text: validationMessage" style="color:Red"></span>

            <div>
                <h2>Details:</h2>
                <hr />

                First Name: <span data-bind="text:name"></span> <br /><br />

                Last Name: <span data-bind=" text:lastName"></span><br /><br />

                Age: <span data-bind="text:age"></span><br />

                <button data-bind="click:save">Submit</button>

                <p>Usuarios: <select data-bind="options:users, value:name" type="text"></select></p>

            </div>




<script src="resources/js/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="resources/js/knockout-3.0.0.js" type="text/javascript"></script>

<script type="text/javascript" src="resources/js/viewModel.js"> </script>

</body>
</html>
Was it helpful?

Solution

don't use this.users() and use prototype for save method also.

viewModel.prototype.loadUsers = function() {
    var tmp = this.users;
    $.get("/vacation_booking/getUsers", function (data) {
        tmp(ko.toJS(data));
        log.info("Usuarios:" + data);

    });

}
viewModel.prototype.save = function(){

// var jsonData = ko.toJSON(viewModel);
// alert("Could now send this to server: " + JSON.stringify(jsonData));
 $.ajax({
    url: "/vacation_booking/save",
    dataType: "json",
    type: "POST",
    data: "name=" + this.name() + "&lastName=" + this.lastName() + "&age=" + this.age(),
    success: function(data){
        alert("Successful");
    },
    failure: function(){
        alert("Unsuccessful");
    }
  });
}

second thing you can return json data directly from controller. check this sample at fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top