comfreakph
comfreakph

Reputation: 541

how can I pass the data using knockoutjs model to mvc viewmodel?

I have this ViewModel in MVC

public class SignupViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string ShoeSize { get; set; }
    public string DressSize { get; set; } 
}

and In my controller

    [Route("register")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Register(SignupViewModel model)
    {

        return Json(new {success=true });

    }

and in my ko script

var signupModel = function () {
var self = this;

self.FirstName = ko.observable("");
self.LastName = ko.observable("");
self.Email = ko.observable("");
self.Username = ko.observable("");
self.Password = ko.observable("");
self.ShoeSize = ko.observable("");
self.DressSize = ko.observable("");};

var viewModel = function () {
var self = this;

self.SignupModel = new signupModel();

self.SubmitForm = function () {
    $.post("/Signup", {
            __RequestVerificationToken: $("input[name='__RequestVerificationToken']").val(),
            model: self.SignupModel,
        }, function (result) {
            alert(result.success);
    });
};};
$(document).ready(function () {
    var model = new viewModel();

    ko.applyBindings(model);
});

When I try to do POST using ajax with the ko SignupViewModel to MVC controller viewmodel it doesnt catch the data from ko js viewmodel. anybody can suggest whats missing in my code? thanks

Upvotes: 0

Views: 935

Answers (1)

GSerjo
GSerjo

Reputation: 4778

You're trying to send SignupModel ViewModel with observable, so MVC doesn't know how to bind observable properties to appropriate properties of your MVC model.

You have to convert observable model to plaint JSON thru ko.toJSON. Take a look "Loading and Saving JSON data" for additional info

Upvotes: 2

Related Questions