开发者

Knockout JS + Sending to MVC 3

I've got the following 开发者_如何学Ccode, 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


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


I think first of all you should change: gradeSelected: ko.observable(Grades[0]) And maybe you'd want to change grades to an observableArray. I'd place this in a comment, but can't yet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜