0

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

这是在客户端

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

我的视图模型

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

我的控制器操作viewModel.Authors 不为空,但计数为 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"}]"
4

2 回答 2

1

只需更换

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

和:

articleViewModel.Authors = appViewModel.authors;

您对 Authors 数组进行双重 JSON 编码,这是不必要的。

于 2013-03-17T17:38:49.940 回答
1

感谢达林,我设法弄清楚显然解决方案是更换

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

articleViewModel.Authors = $.parseJSON(ko.toJSON(appViewModel.authors))
于 2013-03-21T02:02:52.480 回答