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