Using Knockoutjs to fetch and display server-side data within the MVC framework

My goal is to initialize my knockoutjs viewmodel with data from the server. In my ASP.Net MVC project, I achieve this by passing a mvc viewmodel to the view:

public ActionResult Edit(int cvId)
{
    CV cv = repository.FindCV(cvId);

    //auto mapper mapping
    Mapper.CreateMap<CV, MyCVViewModel>();
    Mapper.CreateMap<Company, MyCompanyViewModel>();
    Mapper.CreateMap<Education, MyEducationViewModel>();
    Mapper.CreateMap<Reference, MyReferenceViewModel>();
    var model = Mapper.Map<CV, MyCVViewModel>(cv);

    return View(model);
}

Within the view, I stringify the viewmodel into JSON and bind it to the knockoutjs viewmodel for data population:

//mvc viewmodel
@model Taw.WebUI.Models.MyCVViewModel
//convert
@{
    var json = @Html.Raw(Model.ToJson());
}

//lastly bind
<script type="text/javascript">
    // Activate knockout binding
    var viewModel = new CVViewModel(@json);
    ko.applyBindings(viewModel);
</script>

In my knockout javascript file, I define how the knockout viewmodel will be populated with the fetched data:

var CVViewModel = function (data) {
    var self = this;

    //list view model
    self.title = ko.observable(data.title);
    self.statement = ko.observable(data.statement);
    self.reference = ko.observable(data.reference);
    self.companies = ko.observableArray(data.companies);
    self.educations = ko.observableArray(data.educations);
    self.references = ko.observableArray(data.references);
}

All values are successfully populated at this stage.

The resulting JSON string shows that only title and statement changes, not values within company section.

In order to save these edited values, I need to track what has been modified or deleted on the server side using MVC and entity framework.

Update

In my knockout javascript file, I have defined observables but need help defining them within the observablearray:

function Company() {
    this.companyName = ko.observable();
    this.jobTitle = ko.observable();
    this.description = ko.observable();
    this.startDate = ko.observable();
    this.endDate = ko.observable();
}

Answer №1

Here is the solution to your first question:

In order to resolve the issue, you must utilize ko.observable for each element in the array.

For instance, check out this example: jsfiddle

function CVViewModel(data) {
    var self = this;

    //list view model
    self.title = ko.observable(data.title);
    self.companies = ko.observableArray(data.companies.map(Company));
}

function Company(data) {
    if (!(this instanceof Company)){
        return new Company(data);
    }
    this.companyName = ko.observable(data.companyName || '');
    this.jobTitle = ko.observable(data.jobTitle || '');
    this.description = ko.observable(data.description || '');
    this.startDate = ko.observable(new Date(data.startDate) || '');
    this.endDate = ko.observable(new Date(data.endDate) || '');
}

By binding the company observables to the UI, each element in the array within the viewmodel will remain synchronized.

As for your second inquiry, I suggest utilizing an ORM such as breeze.js, which manages change tracking on your behalf. Breeze.js also offers a helpful tutorial that incorporates knockout.js.

Answer №2

The issue lies in attempting to update items within the ObservableArray. The purpose of an ObservableArray is simply to manage the array model, so any changes made to the companies observable will be reflected in the array as well. To modify the array items, each item within the ObservableArray must also be made Observable.

For more information on this topic, please refer to this post:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can a pledge be honored at a precise moment?

I have implemented transitions on my web page. When clicked, everything fades out to an opacity of 0 over a duration of 1 second. Then, a new page is swapped in and everything fades back in to an opacity of 1 over another 1-second duration. The issue aris ...

Utilizing React to customize JVectorMap markers

Having an issue with a marker appearing in my React project https://i.stack.imgur.com/hkqnZ.jpg The markers are displaying correctly, but there is a persistent initial marker at 0,0 that I can't remove. Removing the 'markers' property from ...

Developing authentication functionality for user login and logout using the C# programming language

Here is the code for my Login Page Controls: <table class="auto-style9"> <tr> <td class="auto-style12" colspan="2" style="font-family: Georgia; font-size: medium; font-weight: bold; text-transform: uppercase; c ...

Struggling to Deploy Application with ASP.NET Core 1.1

I'm having issues running a dotnet publish command on my Linux server to compile my web application. The error message indicates that my project.json file is missing. Before providing a solution, there have been recent changes that need to be taken i ...

Angular: Incorporating a custom validation function into the controller - Techniques for accessing the 'this' keyword

I'm currently working on implementing a custom validator for a form in Angular. I've encountered an issue where I am unable to access the controller's this within the validator function. This is the validator function that's causing tr ...

In Firefox, using the new Date function within a string does not function as expected

Why does the last log in the code snippet below not work in Firefox? (function() { String.prototype.toDate = function() { return new Date(this); }; console.log(Date.parse("2012-01-31")); console.log(new Date("2012-01-31")); c ...

"Modify the MySQL database each time a user changes the value in a

As a student, I am looking to update value(s) whenever a student changes the value(s) in the correction or update form. So far, I have been able to retrieve and display values in text boxes based on the name selected from a dropdown list from the database ...

Manipulating Hyperlinks outside the Angular JS applicationIn certain cases, Angular JS

This is my first attempt at creating a single page app. The app's content is contained within the page like a widget, functioning similar to pagination. In the header, I have links that are not related to the angular app. The link structure looks lik ...

Unexpected behavior in React-Native when filtering array objects

I am currently working on a react-native project where I am dealing with an array object that is being fetched from the backend. Here is a snippet of the Array. { "2010":[ { "id":1243, "eventName": ...

When utilizing the `useLocation` hook, the location information appears to be missing

When utilizing a HashRouter, and inside a component making use of useLocation, there seems to be an inconsistency between the window.location object and the location object retrieved from useLocation. While writing this, I have observed that there might b ...

Utilize Javascript to extract information from an array of XML objects

I have an XML object that I need to parse in order to extract startdate and end date data. My goal is to compare and group appointments with the same date together, but I don't have much experience manipulating XML - I'm more comfortable with JSO ...

Utilizing Angular to automatically extract keys from nested objects in a response

In my Angular application, I am facing a challenge with accessing nested responses from the server. The data structure contains multiple responses within one parent object, and I am struggling to dig deeper into it. Here is the code snippet I have so far: ...

Receiving data dynamically from Highcharts results in an additional legend appearing in the chart display

I am currently looking for a solution to dynamically create highcharts series in my project. Although I have tried using the addSeries method, I am encountering an issue where an extra legend is appearing unnecessarily. If you are aware of any alternative ...

Several different forms are present on a single page, and the goal is to submit all of the data at

Looking for assistance with combining Twitter and Google data entry at once. Here's the code I've developed: Please guide me on how to submit Twitter and Google details together. <html> <head> <script type="text/javascript">< ...

Ways to package object fields within an array

I am in possession of an object with various properties, ranging from arrays to objects. My goal is to transform the object so that each sub field is encapsulated within an array. For instance: "head": { "text": "Main title", "su ...

Navigating a single page application with the convenience of the back button using AJAX

I have developed a website that is designed to function without keeping any browser history, aside from the main page. This was primarily done for security reasons to ensure that the server and browser state always remain in sync. Is there a method by whi ...

Dynamic Form Submission - Displaying Notifications for Success and Failure

While I have managed to successfully submit my form using PHP, I am currently facing some challenges with AJAX. Whenever I submit the form, an error message pops up as if 'res' is false instead of true. Despite my efforts to troubleshoot and rese ...

Transferring data securely via URLs

I need advice on securing a JavaScript function that passes values into URLs in order to navigate to another page. What precautions should I implement to prevent manipulation of this process? This is the code snippet I am currently using: window.location ...

Is indexed coloring available for vertices in three.js?

I have recently started exploring the world of three.js and I am aware that there is a way to color vertices in three.js. However, I am currently researching whether it is possible to implement indexed colors for vertices in three.js or WebGL. Specifically ...

Getting Started with a RabbitMQ Client Connection in a Web Application using .NET

In the process of developing a RabbitMQ client bus class for a .NET Framework web application. The class structure is quite simple: public class RabbitConnection { private readonly IConnection conn; public RabbitConnection() { try { ...