本文介绍了knockoutjs与ko.utils.postJson问题提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我跟着的文章使用ko.utils.postJson从控制器提交数据并导航到不同的视图

我用 ko.utils.postJson(location.href,{型号:ko.toJson(视图模型)}); 提交提交数据,但该模型服务器有空的属性。

ko.utils.postJson(location.href,{型号:视图模型}); 太失败了。

客户视图模型比服务器模型的附加属性,但我相信,如果它与$阿贾克斯post方法有效,那它就应该KO岗位工作

它的工作,如果我通过模型下

  ko.utils.postJson(location.href,
    {模型:{P1:this.p1(),P2:this.p2(),P3:this.p3()}});

我必须在提交之前每个属性映射?它也确实迷惑时使用()为视图模型的属性。

服务器code

  [HttpPost]
        公众的ActionResult SearchProperty([FromJson]为MyModel模型)
        {
            尝试
            {
                返回视图(XYZ,模型);
            }
            赶上(例外五)
            {
            }
        }


解决方案

淘汰赛提供了一个实用的功能,将含有转观测到一个纯JavaScript对象的对象。效用函数是 ko.toJS 。所以,如果你做的:

  {模式:ko.toJS(视图模型)}

然后,将处理展开所有观测的。

此外,还有另外一个功能 ko.toJSON ,会做一个 ko.toJS 然后执行 JSON.stringify 的结果。当你真正需要的,而不是一个JavaScript对象JSON这是有用的。

I followed the http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/ article to submit data using ko.utils.postJson and navigate to a different view from the controller

I used ko.utils.postJson(location.href, {model: ko.toJson(viewModel)}); to submit the data but the model submitted to the server has empty properties.

ko.utils.postJson(location.href, {model: viewModel}); failed too.

The client viewModel has additional properties than the server model but I believe if it works with $ajax post method, it should work with KO post

It worked if I pass the model as under

ko.utils.postJson(location.href, 
    {model: {P1:this.p1(), P2:this.p2(), P3: this.p3()}}); 

Do I have to map each property before submission? Its also really confusing when to use () for viewModel properties

Server Code

 [HttpPost]
        public ActionResult SearchProperty([FromJson]MyModel model)
        {
            try
            {
                return View("XYZ", model);
            }
            catch (Exception e)
            {
            }
        }
解决方案

Knockout provides a utility function that will turn an object containing observables into a plain JavaScript object. The utility function is ko.toJS. So, if you did:

   { model: ko.toJS(viewModel) }

Then, it would handle unwrapping all of your observables.

Additionally, there is another function ko.toJSON that will do a ko.toJS and then do JSON.stringify on the result. This is useful when you really need JSON instead of a JavaScript object.

这篇关于knockoutjs与ko.utils.postJson问题提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 16:58