Bobby Tables
Bobby Tables

Reputation: 3013

Post knockout observable array as object property asp.net mvc

I'm trying to post an ko.observable array as part of of an object, all that data reaches the server ok except for the array which is not null but has a count of zero.

This is on the client side

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

My viewModel

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

My controller action viewModel.Authors is not null but has a count of 0

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

The ko array outputed from javascript

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

Upvotes: 0

Views: 2738

Answers (2)

Bobby Tables
Bobby Tables

Reputation: 3013

Thanks to Darin i managed to figure it out apparently the solution was to replace

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

with

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

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Simply replace

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

with:

articleViewModel.Authors = appViewModel.authors;

You are double JSON encoding the Authors array which is not necessary.

Upvotes: 1

Related Questions