Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7977811
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T09:18:57+00:00 2026-06-04T09:18:57+00:00

I am using knockout (KO) in my MVC project. I create an MVC model

  • 0

I am using knockout (KO) in my MVC project. I create an MVC model (for a grid) on server and pass it to the view. On the view it is serialized and converted into a KO model (using ko.mapping) which in turn is used for binding. That binding is then used in HTML for grid creation.

This is how my MVC grid model looks like which in turn gets converted to corresponding KO model by ko.mapping:

public class GridModel
    {
        /// <summary>
        /// Grid body for the grid.
        /// </summary>
        public GridBodyModel GridBodyModel { get; set; }

        /// <summary>
        /// Grid context.
        /// </summary>
        public GridContext GridContext { get; set; }

        /// <summary>
        /// Grid header for the grid.
        /// </summary>
        public GridHeaderModel GridHeader { get; set; }
    }

public class GridBodyModel
    {
        /// <summary>
        /// List of grid body rows.
        /// </summary>
        public IList<GridRowModel> Rows { get; set; }
    }


public class GridContext
    {
        /// <summary>
        /// Total number of pages. Read-only.
        /// </summary>
        public int TotalPages{ get; set; }
    }

public class GridHeaderModel
    {
        /// <summary>
        /// List of grid header cells.
        /// </summary>
        public IList<GridHeaderCellModel> Cells { get; set; }
    }

As it is clear the main model class GridModel is made of following classes which are present as properties:

GridBodyModel: Has list of rows to be rendered in the grid body.

GridContext: Has total number of pages as a property. It has other properties as well but that is out of scope of this discussion.

GridHeaderModel: Has a list of cells that has to be displayed in header of the grid.

Then I have this script that will execute on fresh page load.

$(document).ready(function () {
        // Apply Knockout view model bindings when document is in ready state.
        ko.applyBindings(Global_GridKOModel, document.getElementById("gridMainContainer"));
    });

// Serialize the server model object. It will be used to create observable model.
Global_GridKOModel = ko.mapping.fromJS (<%= DataFormatter.SerializeToJson(Model) %>);

Global_GridKOModel is global javascript variable.
Model is the MVC grid model coming from server.

A user can perform further search on the page again. I handle this by posting new search criteria via Ajax. On this post a new MVC model is created and is sent back as Ajax response. This new MVC Model is then simply used to update Global_GridKOModel using ko.mapping which in turn refreshes the grid (with new data) that was constructed earlier on fresh page load. This is how I am doing it.

$.ajax({
        url: destUrl,
        data: dataToSend
        success: function (result) {
            ko.mapping.fromJS(result, Global_GridKOModel);
        },
        error: function (request, textStatus, errorThrown) {
            alert(request.statusText);
        }
    });

Everything is working fine except in the following scenario.

An Ajax request is made for which no result is returned i.e. GridBodyModel and GridHeaderModel is null in the model GridModel. That time grid rightly shows that no record has been found. This is correct. This happens by the following HTML binding.

<!-- When no record is found. -->
<div data-bind="ifnot: GridContext.GridPager.TotalPages() > 0">
    No record(s) were found.
</div>

<!-- This is actual grid table container. This is binded when records are found -->
<div data-bind="if: GridContext.TotalPages() > 0">

Grid construction happens here

</div>

Now after this if another Ajax request is made but this time records are returned (I have checked the response with firebug and it is confirmed that records are indeed returned). This time grid construction happens wherein various observable arrays are accessed. For example, to construct pager for the grid following is a piece of HTML binding I wrote.

<td data-bind="attr:{colspan: GridHeader.Cells().length }">

This time KO throws following error which can be seen in firebug.

Unable to parse bindings.
Message: TypeError: GridHeader.Cells is not a function;
Bindings value: attr:{colspan: GridHeader.Cells().length }

It work fine so long there are records being returned but it breaks after no record is returned as explained above. Please note GridHeader was null in earlier response when no records were returned. I smell something fishy in ko.mapping. I think there is some problem while mapping observable array.

So what is it that I am not doing right? Anyone please?

Please feel free to ask for clarification if I have not mentioned things clearly.

Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T09:18:59+00:00Added an answer on June 4, 2026 at 9:18 am

    The actual reason for behavior is that originally GridHeader is javascript object, but when your return call mapping with null for GridHeader property, it will become observable with null value, and on all future updates it will still be an observable.

    Workarounds are (choose one):

    1. Do not return null values for child models (return empty objects instead) – I think it is preferred way
    2. Or – before calling map, run
      Global_GridKOModel.GridHeader = null; (this will ensure that after update GridHeader will not be an observable)
    3. Or – after mapping, call
      Global_GridKOModel.GridHeader = ko.unwrapObservable(Global_GridKOModel.GridHeader);

    Full explanation of behavior you have is in code below (copy on jsfiddle – http://jsfiddle.net/nickolsky/zrBuL/9/ )

    console.log('step1');
    var vm = ko.mapping.fromJS({ body: { children: [ 1, 2, 3]} });
    console.log(vm.body.children()[1]); //prints 2
    
    console.log('step2');
    ko.mapping.fromJS({ body: { children: [ 4, 5, 6]} }, vm);
    console.log(vm.body.children()[1]); //prints 5
    
    console.log('step3');
    //after next call, vm.body is no longer variable - it is now observable
    ko.mapping.fromJS({ body: null }, vm);
    console.log(vm.body); //prints observable
    console.log(vm.body()); //prints null
    
    console.log('step4');
    //and it will remain observable for next call
    ko.mapping.fromJS({ body: { children: [ 7, 8, 9]} }, vm);
    console.log(vm.body().children()[1]); //prints 8
    console.log(vm.body().children().length); //prints 3
    console.log(vm.body); //prints observable function body
    console.log(vm.body()); //prints object
    
    //workaround for null issue - we can reset it to be null instead of null observable
    //and it will get original behavior
    vm.body = null;
    console.log('step5');    
    ko.mapping.fromJS({ body: { children: [ 7, 8, 9]} }, vm);
    console.log(vm.body.children()[1]); //prints 8 - body is no longer observable again
    ​
    

    For me it looks like design issue of mapping plugin, I was not able to find a way to customize mapping for child viewmodel properties to make sure they won’t become observables if they are null (‘copy’ functionality will make all inner content as non-observable, unfortunatelly).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In ASP.NET MVC there is Model, View and Controller. MODEL represents entities which are
I am using Knockout-JS to bind properties in my view to my view model.
I have an ASP.NET MVC 3 view using Razor and Knockout.js that is not
I see lot and lot of advantage in using Knockout.js in my MVC project
See code (am using Knockout.js over ASP MVC 3): @model List<Person> @{ ViewBag.Title =
I'm building a MVC application which has a heavy client side scripting using Knockout,JQuery
We are submitting an asp.net mvc view form using the knockoutjs postJson util. All
I am using Knockout Js for my view page. I have a requirement where
I've started looking into using Knockout for my team's use; I've been very pleased
Using knockout's mapping plugin, how would I go about displaying the information from and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.