如何使用knockoutjs模型将数据传递给mvc viewmodel?

时间:2014-05-31 22:11:00

标签: c# asp.net-mvc knockout.js

我在MVC中有这个ViewModel

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; } 
}

和我的控制器

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

        return Json(new {success=true });

    }

和我的ko脚本

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);
});

当我尝试使用带有ko SignupViewModel到MVC控制器视图模式的ajax进行POST时,它不会从ko js viewmodel捕获数据。任何人都可以建议我的代码中缺少什么?感谢

1 个答案:

答案 0 :(得分:2)

您尝试使用observable发送SignupModel ViewModel,因此MVC不知道如何将可观察属性绑定到MVC模型的适当属性。

您必须将可观察模型转换为plaint JSON至ko.toJSON。看看" Loading and Saving JSON data"了解更多信息