Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout JS + Sending to MVC 3

I've got the following code, but once it's submitted to the server I'm getting strings of "undefined" instead of null or empty. This is causing issues as I can't perform validation. Any ideas how to prevent this happening when using knockout.

var viewModel = {
        userName: ko.observable(""),
        emailAddress: ko.observable(""),
        verifyEmailAddress: ko.observable(""),
        OptOut: ko.observable(true),
        Grades: ["Grade 1", "Grade 2", "Grade 3", "Grade 4", "Grade 5", "Grade 6"],
        gradeSelected: ko.observable(["Grade 1"])
    };
    ko.applyBindings(viewModel);

    $("#addUser").click(function (e) {
        $.ajax({
            url: 'AddUser',
            dataType: 'json',
            data: JSON.stringify(viewModel),
            type: 'POST',
            success: function (data) {
                $("#errorSection").text(data.Success).show();
            }   
        });
        e.preventDefault();
    });

Thanks in advance

like image 687
RubbleFord Avatar asked May 28 '11 07:05

RubbleFord


1 Answers

Instead of JSON.stringify(viewModel) do ko.toJSON(viewModel), which will unwrap all of the observables first before doing a stringify. Some useful docs here: http://knockoutjs.com/documentation/json-data.html

like image 70
RP Niemeyer Avatar answered Oct 13 '22 21:10

RP Niemeyer