post knockout observable array as object property asp.net mvc

时间:2013-03-17 17:06:26

标签: jquery asp.net ajax asp.net-mvc knockout.js

我正在尝试将ko.observable数组作为对象的一部分发布,所有数据都到达服务器ok,除非数组不为null但计数为零。

这是在客户端

    function submitAsync() {
    var viewModel = constructModel();

    setTimeout(function () {
        $.ajax({
            url: '/Article/Index',
            type: 'POST',
            data: JSON.stringify({ viewModel: viewModel }),
            contentType: 'application/json; charset=utf-8',
        })
    },2000);
    console.log(viewModel);
}

function constructModel(){
    var articleViewModel = {};
    articleViewModel.Authors = ko.toJSON(appViewModel.authors);

    articleViewModel.ArticleData = {};
    articleViewModel.ArticleData.Title = $("#ArticleData_Title").text();
    articleViewModel.ArticleData.CorespondingAuthor = $("#ArticleData_CorespondingAuthor").text();
    articleViewModel.ArticleData.Keywords = $("#ArticleData_Keywords").text();

    articleViewModel.ArticleContent = {};
    articleViewModel.ArticleContent.Abstract = $("#ArticleContent_Abstract").text();
    articleViewModel.ArticleContent.FullText = ArticleContent();

    return articleViewModel;
}

我的viewModel

public class ArticleViewModel
{
    public ArticleData ArticleData { get; set; }
    public ArticleContent ArticleContent { get; set; }
    public ICollection<Author> Authors { get; set; }
}

我的控制器操作 viewModel.Authors不为null但计数为0

[HttpPost]
        public ActionResult Index(ArticleViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                mergeViewModelToCurrentArticle(viewModel);
                _documentPath = GenerateDocument(_currentArticle);
                return RedirectToAction("Success");
            }
            return View();
        }

从javascript中输出的ko数组

Authors: "[{"id":1,"firstName":"User first name","lastName":"user last name","email":"user@gmail.com","phone":"xxxxx","address":"Dunarii Nr.3","fullName":"user full name"}]"

2 个答案:

答案 0 :(得分:1)

简单地替换

articleViewModel.Authors = ko.toJSON(appViewModel.authors);

使用:

articleViewModel.Authors = appViewModel.authors;

你是Authors数组的双JSON编码,这是不必要的。

答案 1 :(得分:1)

感谢Darin,我设法明白解决方案是取代

articleViewModel.Authors = ko.toJSON(appViewModel.authors); 

articleViewModel.Authors = $.parseJSON(ko.toJSON(appViewModel.authors))