Knockout js,mvc 5项目 - 将客户端ViewModel绑定到控制器操作

时间:2016-11-03 12:50:18

标签: asp.net-mvc knockout.js knockout-mapping-plugin

你可以帮我解决这个问题。我成功从服务器ViewModel获取数据。但是,当我尝试将客户端ViewModel从视图保存到Controller Save操作时。我得到空的ViewModel。在示例中我使用的是JavaScriptSerializer。但是,由于存在Newtonsoft扩展,因此建议不要在ASP.NET Core MVC项目中使用。你能帮我采用下面的代码吗?

@{
ViewBag.Title = "Details";
}

@{
     var data = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
}

@section scripts
{
     <script src="~/lib/knockout/dist/knockout.js"></script>
     <script src="~/lib/knockout-mapping/knockout.mapping.js"></script>
     <script src="~/js/realtyvm.js"></script>
     <script type="text/javascript">
        $(function () {
        var realtyViewModel = new RealtyViewModel(@Html.Raw(data));
        ko.applyBindings(realtyViewModel);
        });
     </script>
}

/* Realty Client ViewModel */

(function () {
RealtyViewModel = function (data) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);

    self.save = function () {
        $.ajax({
            url: "/App/Save/",
            type: "POST",
            data: ko.toJSON(self),
            contentType: "application/json",
            success: function (data) {
                if (data.realtyViewModel != null)
                    ko.mapping.fromJS(data.realtyViewModel, {}, self);
            }
        });
    }

}
})();

这看起来如何看待控制器动作:

    public ActionResult Create()
    {
        RealtyViewModel realtyViewModel = new RealtyViewModel();
        return View(realtyViewModel);
    }

    public JsonResult Save(RealtyViewModel realtyViewModel)
    {
        Realty realty = new Realty();
        realty.Title = realtyViewModel.Title;
        realty.Description = realtyViewModel.Description;
        realty.RealtyType = realtyViewModel.RealtyType;

        _repository.InsertRealty(realty);
        _repository.Save();

        realtyViewModel.MessageToClient = string.Format("{0} realty has been added to the database.", realty.Title);

        return Json(new { realtyViewModel });
    }

更新,我打开了XHR请求,详情如下:

请求有效负载

{Id: 0, Title: "Te", Description: "te", RealtyType: "te", MessageToClient: null}
Description:"te" Id:0 MessageToClient:null RealtyType:"te" Title:"Te"

响应:

{"realtyViewModel":{"id":0,"title":null,"description":null,"realtyType":null,"messageToClient":" realty has been added to the database."}}

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题,方法是通过将[FromBody]添加到后期操作来指定即将发布的数据。

    public JsonResult Save([FromBody]RealtyViewModel realtyViewModel)
    {
        Realty realty = new Realty();
        realty.Title = realtyViewModel.Title;
        realty.Description = realtyViewModel.Description;
        realty.RealtyType = realtyViewModel.RealtyType;

        _repository.InsertRealty(realty);
        _repository.Save();

        return Json(new { realtyViewModel });
    }