Automatically update viewModel after save to db - asp.net-mvc

What I want to achieve is once the data got saved into database, when it goes back to client, it will automatically update the observable array. But somehow I couldn't make it happen.
This is my Server side code:
[HttpGet]
public JsonResult GetTasks()
{
var tasks = context.ToDoTasks.ToList();
return Json(tasks.Select(c => new TaskViewModel(c)).ToList(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult AddTask(string text, string date)
{
var nTask = new ToDoTask()
{
Text = text,
Date = DateTime.ParseExact(date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture),
IsDone = false,
Order = 1,
};
context.ToDoTasks.Add(nTask);
context.SaveChanges();
return Json(new TaskViewModel(nTask), JsonRequestBehavior.AllowGet);
}
This is my cshtml file code:
<form>
<div class="controls controls-row" style="margin-top:40px;">
<input class="span7" type="text" placeholder="Task to do" style="margin-right:4px;" id="oText">
<div id="task-date" class="input-append date">
<input data-format="MM/dd/yyyy" type="text" placeholder="MM/dd/yyyy" name="taskDate" id="oDate" />
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar">
</i>
</span>
</div>
<button class="btn" type="submit" style="margin-top:-10px;" data-bind="click: save">+</button>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox"> Mark all as complete
</label>
</div>
<div id="task-section" style="margin-top:20px;">
<ul data-bind="foreach: Tasks">
<!-- ko if: IsDone -->
<li>
<span><input type="checkbox" style="margin:-5px 5px 0px 0px;" data-bind="checked: IsDone" /></span>
<del><span data-bind="text: Text"></span></del>
<del><span class="task-date" data-bind="text: Date"></span></del>
</li>
<!-- /ko -->
<!-- ko ifnot: IsDone -->
<li>
<span><input type="checkbox" style="margin:-5px 5px 0px 0px;" data-bind="checked: IsDone" /></span>
<span data-bind="text: Text"></span>
<span class="task-date" data-bind="text: Date"></span>
</li>
<!-- /ko -->
</ul>
</div>
<div class="clearfix" style="margin-top:30px;">
<span class="pull-left" style="font-weight:bold;"><span data-bind="text: oItemLeft"></span> item left</span>
<span class="pull-right badge" style="cursor:pointer;" data-bind="click: remove">Clear # completed item</span>
</div>
</form>
And finally my JS:
var ViewModel = function (data) {
var self = this;
self.Tasks = ko.mapping.fromJS(data, {}, self.Tasks);
self.oItemLeft = ko.computed(function () {
var i = 0;
data.forEach(function (entry) {
if (!entry.IsDone) i++;
});
return i;
});
self.save = function () {
$.ajax({
url: "Home/AddTask",
type: "POST",
data: { text: $('#oText').val(), date: $('#oDate').val() },
success: function (response) {
ko.mapping.fromJS(response, ViewModel);
}
});
};
self.remove = function () {
alert('delete');
}
}
$(function () {
$.getJSON("/Home/GetTasks/", null, function (data) {
ko.applyBindings(new ViewModel(data));
});
// for datepicker
$('#task-date').datetimepicker({
language: 'pt-BR',
pickTime: false
});
});

self.save = function () {
$.ajax({
url: "Home/AddTask",
type: "POST",
data: { text: $('#oText').val(), date: $('#oDate').val() },
success: function (response) {
var task = ko.mapping.fromJS(response);
self.Tasks.push(task);
}
});
};
Also for oItemLeft you should be referring to self.Tasks instead of data:
self.oItemLeft = ko.computed(function () {
var i = 0;
self.Tasks().forEach(function (entry) {
if (!entry.IsDone) i++;
});
return i;
});

Related

knockout binding mvc not working

I experimenting something with mvc and knockout.js but maybe a have binding problem.
My viewmodel is:
var urlPath = window.location.pathname;
var currencyVm = function () {
var self = this;
var validationOptions = { insertMessages: true, decorateElement: true, errorElementClass: 'errorFill' };
ko.validation.init(validationOptions);
//ViewModel
self.ID = ko.observable(0);
self.Id_Region = ko.observable("");
self.Description = ko.observable("");
self.Symbol = ko.observable("");
self.PayPalCode = ko.observable("");
self.IFSCode = ko.observable("");
self.isGridVisible = ko.observable(true);
self.isEditVisible = ko.observable(false);
self.isAddVisible = ko.observable(false);
//Objects ---------------------------------------------
self.Currency = ko.observable();
self.Currencys = ko.observableArray([]);
//Methods ---------------------------------------------
//Edit
self.editCurrency = function (dataItem) {
self.isGridVisible(false);
self.isEditVisible(true);
self.ID = ko.observable(dataItem.ID);
self.Id_Region = ko.observable(dataItem.Id_Region);
self.Description = ko.observable(dataItem.Description);
self.Symbol = ko.observable(dataItem.Symbol);
self.PayPalCode = ko.observable(dataItem.PayPalCode);
self.IFSCode = ko.observable(dataItem.IFSCode);
//var vm = ko.mapping.fromJS(dataItem);
//self.Currency(vm);
};
//Add
self.addCurrency = function () {
self.isGridVisible(false);
self.isAddVisible(true);
self.isEditVisible(false);
self.reset();
}
// Cancel Edit
self.cancelEdit = function () {
self.isEditVisible(false);
self.isGridVisible(true);
}
// Cancel Add
self.cancelAdd = function () {
self.isAddVisible(false);
self.isGridVisible(true);
}
//Reset
self.reset = function () {
self.ID(0);
self.Id_Region("");
self.Description("");
self.Symbol("");
self.PayPalCode("");
self.IFSCode("");
}
//Actions --------------------------------------------------
var Currency = {
ID: self.ID,
Id_Region: self.Id_Region,
Description: self.Description,
Symbol: self.Symbol,
PayPalCode: self.PayPalCode,
IFSCode: self.IFSCode
};
//Create
self.createCurrency = function () {
$.ajax({
url: "/Currency/CreateCurrency",
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Currency),
success: function (data) {
self.isEditVisible(false);
self.isAddVisible(false);
self.isGridVisible(true);
$("#gridCurrencies").data("kendoGrid").dataSource.read();
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
});
}
// Update
self.updateCurrency = function () {
$.ajax({
url: "/Currency/UpdateCurrency",
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Currency),
success: function (data) {
self.isEditVisible(false);
self.isEditVisible(false);
self.isGridVisible(true);
$("#gridCurrencies").data("kendoGrid").dataSource.read();
}
})
}
//Delete
self.deleteCurrency = function (currency) {
$.confirm({
title: "Delete",
content: "Sure to delete ?",
confirm: function () {
$.ajax({
url: "/Currency/DeleteCurrency",
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(currency),
success: function (data) {
$("#gridCurrencies").data("kendoGrid").dataSource.read();
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
});
},
cancel: function () {
}
});
}
};
in the view I call applybinding and then based on selected row of the Telerik grid I call editCurrency or deleteCurrency.
<script>
var viewModel = null;
$(function () {
viewModel = new currencyVm();
ko.applyBindings(viewModel);
});
function deleteCurrency(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
viewModel.deleteCurrency(dataItem);
}
function editCurrency(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
viewModel.editCurrency(dataItem);
}
</script>
In the markup I have the html elements with the bindings:
Thi is the div for add:
<div class="panel panel-default" data-bind="visible: isAddVisible" style="display:none">
<div class="panel-heading">Add New Currency</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.IFSCode)
<input type="text" data-bind="value: $root.IFSCode, valueUpdate: 'keypress'" class="form-control " />
</div>
<div class="col-md-3">
#Html.LabelFor(model => model.PayPalCode)
<input type="text" data-bind="value: $root.PayPalCode, valueUpdate: 'keypress'" class="form-control " />
</div>
<div class="col-md-3">
#Html.LabelFor(model => model.Symbol)
<input type="text" data-bind="value: $root.Symbol, valueUpdate: 'keypress'" class="form-control " />
</div>
</div>
<div class="row">
<div class="col-md-9">
#Html.LabelFor(model => model.Description)
<input type="text" data-bind="value: $root.Description" class="form-control" />
</div>
</div>
<br />
<div class="row">
<div class="col-md-3">
<input data-bind="click: $root.createCurrency" type="button" class="btn btn-success btn-sm" value="#DbRes.T("Save", "Common")" />
<input data-bind="click: cancelAdd" type="button" class="btn btn-warning btn-sm" value="#DbRes.T("Cancel", "Common")" />
</div>
</div>
</div>
the edit div is like the add div but use different binding like data-bind="value: IFSCode"
The problem is that in add mode it work but when I edit I dont see nothing
in the textbox elements.
Also I use the to debug,
in add mode I can see the observables updating while I type something in textbox,
in edit mode the observables are emtpy and remain while typeing something.
May some body help please to understand what appen to this code
Your help is very appreciated.

knockout.js ul li databinding not proper

HTML
<h4>People</h4>
<ul data-bind="foreach: people">
<li>
<span data-bind="text: name"> </span>
Remove
</li>
</ul>
<button data-bind="click: addPerson">Add</button>
<input type="text" data-bind="value: cardtext" /><br /><br /><br />
JS
function AppViewModel() {
var self = this;
self.cardtext=ko.observable();
self.people = ko.observableArray([
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
self.addPerson = function() {
self.people.push({ name: self.cardtext });
};
self.removePerson = function() {
self.people.remove(this);
}
}
ko.applyBindings(new AppViewModel());
This is the result
The problem is that the textbox keep adding new elements but the previous newly added elements keep getting updated by the new elements.
3rd element was 3rd element
4th element was 4th element
when I added 5th element the 3rd and the 4th element get updated by 5th element. why it is that? what I am doing wrong?. I have no idea.
You just need to add () at the end of self.cardtext(). If you don't put the parenthesis, what it will do is it will push the observable object of cardtext to the array instead of its value. So when you modify cardtext from the textbox, it will also modify the previous object that was pushed.
function AppViewModel() {
var self = this;
self.cardtext=ko.observable();
self.people = ko.observableArray([
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
self.addPerson = function() {
self.people.push({ name: self.cardtext() });
};
self.removePerson = function() {
self.people.remove(this);
}
}
ko.applyBindings(new AppViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<h4>People</h4>
<ul data-bind="foreach: people">
<li>
<span data-bind="text: name"> </span>
Remove
</li>
</ul>
<button data-bind="click: addPerson">Add</button>
<input type="text" data-bind="value: cardtext" /><br /><br /><br />

AngularJS doesn't work in MVC Partial Views

I'm currently working on a ASP.NET MVC project. The sites of the web application are created with Bootstrap. Later I added some AngularJS script to be able to translate the page into different languages. This works fine for all the pages, but not so if a partial view is loaded from a page.
So, for example I have a page to search for rollout objects by name or host name. On the page all the angular expressions in curly braces are evaluated properly and are replaced with strings in several languages by using a translate script. Now if I filter the objects by one of the three attributes the partial view for that page is loaded showing the results of the search, but here are the angular expressions not evaluated and it just shows the expressions themselves.
Here is the page where it works properly:
#{
ViewBag.Title = "{{ 'ROLLOUT-OBJECT_MANAGEMENT.TITLE' | translate }}";
}
<!-- html -->
<div style="font-size: 20px; margin-top: 20px; margin-bottom: 20px;">
<div class="gray-background list-group-item" translate="{{'ROLLOUT-OBJECT_MANAGEMENT.TITLE'}}"></div>
</div>
<div class="list-group">
<div class="gray-background list-group-item">
<div class="row margin-bottom">
<div class="col-md-3">
<h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.FIRST_NAME'}}"></h6>
</div>
<div class="col-md-3">
<h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.SURNAME'}}"></h6>
</div>
<div class="col-md-3">
<h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.HOST_NAME'}}"></h6>
</div>
</div>
<div class="row margin-bottom">
<div class="col-md-3">
<!-- referenced in getPartial() -->
<input type="text" class="form-control" id="iFirstName" name="iFirstName" placeholder="">
</div>
<div class="col-md-3">
<!-- referenced in getPartial() -->
<input type="text" class="form-control" id="iSurName" name="iSurName" placeholder="">
</div>
<div class="col-md-3">
<!-- referenced in getPartial() -->
<input type="text" class="form-control" id="iHostName" name="iHostName" placeholder="">
</div>
<div class="col-md-3">
<!-- getPartial() added to click through javascript-->
<button type="submit" class="btn btn-primary btn-block" id="iButton"><span translate="{{'ROLLOUT-OBJECT_MANAGEMENT.BUTTON_SEARCH'}}"></span><span class="white-color glyphicon glyphicon-search"></span></button>
</div>
</div>
</div>
</div>
<div class="list-group">
<div class="gray-background list-group-item">
<h5><span translate="{{'ROLLOUT-OBJECT_MANAGEMENT.RESULTS'}}"></span><span class="purple-color glyphicon glyphicon-globe"></span></h5>
</div>
<!-- referenced in getPartial() -->
<div class="gray-background list-group-item">
<div class="row">
<div class="col-md-12" id="partialViewContainer">
#{Html.RenderPartial("_RolloutObjectManagementResultsPartial");}
</div>
</div>
</div>
</div>
<!-- layout -->
#Styles.Render(
"~/content/chosen/chosen.css",
"~/content/chosen/prism.css",
"~/content/chosen/style.css",
"~/content/bootstrap.css",
"~/content/Site.css")
<!-- javascript -->
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen/chosen.jquery.js"></script>
<script src="~/Scripts/chosen/prism.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
</script>
<script>
//add functionality to button
$('#iButton').click(function () {
getPartial('0');
});
</script>
<script>
function previous() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
if (temp > 0) {
temp = --temp;
}
getPartial(temp);
}
function next() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
temp = ++temp;
getPartial(temp);
}
</script>
<script>
function getPartial(newPage) {
//get search values
var tempFirst = document.getElementById("iFirstName");
var tempSur = document.getElementById("iSurName");
var tempHost = document.getElementById("iHostName");
var firstResult = tempFirst.value;
var surResult = tempSur.value;
var hostResult = tempHost.value;
//ajax call
$.ajax({
url: "_RolloutObjectManagementResultsPartial",
type: "POST",
data: { firstName: firstResult, surName: surResult, hostName: hostResult, page: newPage, count: 10 },
dataType: "html",
error: function (xhr) {
//alert(xhr.responseText);//debug
},
success: function (result) {
$("#partialViewContainer").html(result).find("select").each(function () {
$(this).chosen({});
})
},
complete: function () {
//alert("everything worked");//debug
}
});
}
</script>
And here is the partial view where it doesn't work (important are the expressions in {{...}}:
<!-- Import needed namespaces -->
#using RolloutTool.BusinessLayer.Foundation
#using RolloutTool.Utility
<!-- Initializing needed variables -->
#{
List<RolloutObject> RolloutObjects = ViewContext.Controller.ViewBag.RolloutObjects;
List<Cluster> Clusters = ViewContext.Controller.ViewBag.Clusters;
string name = "";
int count = 0;
string rowID = "";
int page = 0;
if (ViewContext.Controller.ViewBag.Page != null)
{
page = ViewContext.Controller.ViewBag.Page;
}
}
<!-- html elements -->
<div class="row">
<div class="col-md-12">
<table class="table">
<thead>
<tr>
<th style="width:25%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.EMPLOYEE'}}"></h6></th>
<th style="width:20%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.WORK_STATION'}}"></h6></th>
<th class="text-center" style="width:15%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.EDIT'}}"></h6></th>
<th class="text-center" style="width:25%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.CLUSTER'}}"></h6></th>
<th class="text-center" style="width:15%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.ASSIGN'}}"></h6></th>
</tr>
</thead>
<tbody>
<!-- creating all RolloutObject Table rows -->
#foreach (RolloutObject ro in RolloutObjects)
{
<!-- generating rowID -->
rowID = "row" + Convert.ToString(count);
count++;
<!-- generating the full employee name -->
name = Functions.TryGetValue(ro.Employee.FirstName) + " " + Functions.TryGetValue(ro.Employee.SecondName) + " " + Functions.TryGetValue(ro.Employee.Name);
<tr id="#rowID">
<td>#name</td>
<td id="#Convert.ToString(rowID + "_hn")">#Convert.ToString(Functions.TryGetValue(ro.Hostname))</td>
<!-- generate link to right rolloutobjectedit -->
<td class="text-center"><span class="btn-pencil glyphicon glyphicon-pencil blue-color glyph-hov" onclick="location.href='#Url.Action("RolloutObjectEdit", "RolloutObject", new {hostName = ro.Hostname })'"></span></td>
<!-- generating the link for cluster addition and populating cluster dropdown -->
<td class="text-center">
<div class="row">
<div class="col-sm-12">
<select class="chosen-select no-margin" style="width:100%" id="#Convert.ToString(rowID + "_cl")" name="iCluster" data-placeholder="Cluster">
#if (ro.Cluster != null)
{
<option selected>#Convert.ToString(Functions.TryGetValue(ro.Cluster.Name))</option>
}
else
{
<option></option>
}
#foreach (Cluster cluster in Clusters)
{
<option>#Convert.ToString(Functions.TryGetValue(cluster.Name))</option>
}
</select>
</div>
</div>
</td>
<td class="text-center"><span class="btn-ok glyphicon glyphicon-ok green-color glyph-hov" onclick="callAjax('#rowID')" /></td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input class="hidden" id="hPage" value="#Convert.ToString(page)" />
<nav>
<ul class="pager">
<li class="pull-left"><a class="btn-paging glyphicon glyphicon-arrow-left" onclick="previous()"></a></li>
<li class="pull-right"><a class="btn-paging glyphicon glyphicon-arrow-right" onclick="next()"></a></li>
</ul>
</nav>
</div>
</div>
<!-- javascript -->
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen/chosen.jquery.js"></script>
<script src="~/Scripts/chosen/prism.js"></script>
<script>
function callAjax(idRow) {
//get row values
var tempTD = document.getElementById(idRow + "_hn");
var tempSelect = document.getElementById(idRow + "_cl");
var tempHostName = tempTD.textContent;
var tempCluster = tempSelect.options[tempSelect.selectedIndex].text;
//ajax call
$.ajax({
url: "AddToCluster",
type: "POST",
data: { clusterName: tempCluster, hostName: tempHostName },
dataType: "html",
error: function (xhr) {
alert(xhr.responseText);
},
success: function (result) {
},
complete: function () {
//alert("everything worked");//debug
}
});
}
</script>
<script>
function previous() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
if (temp > 0) {
temp = --temp;
}
getPartial(temp);
}
function next() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
temp = ++temp;
getPartial(temp);
}
</script>
<script>
function getPartial(newPage) {
//get search values
var tempFirst = document.getElementById("iFirstName");
var tempSur = document.getElementById("iSurName");
var tempHost = document.getElementById("iHostName");
var firstResult = tempFirst.value;
var surResult = tempSur.value;
var hostResult = tempHost.value;
//ajax call
$.ajax({
url: "_RolloutObjectManagementResultsPartial",
type: "POST",
data: { firstName: firstResult, surName: surResult, hostName: hostResult, page: newPage, count: 10 },
dataType: "html",
error: function (xhr) {
alert(xhr.responseText);
},
success: function (result) {
$("#partialViewContainer").html(result).find("select").each(function () {
$(this).chosen({});
})
},
complete: function () {
//alert("everything worked");//debug
}
});
}
</script>
This is the _Layout.cshtml where the scripts are contained and loaded:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - {{ 'TITLE.PROGRAM' | translate }}</title>
#Styles.Render(
"~/Content/css",
"~/Content/flag-icon-css-master/assets/docs.css",
"~/Content/flag-icon-css-master/css/flag-icon.min.css",
"~/Content/Site.css")
<script src="~/Scripts/angular/angular.js"></script>
<script src="~/Scripts/angular/angular-translate.js"></script>
<script src="~/Scripts/angular/angular-cookies.min.js"></script>
<script src="~/Scripts/angular/translate.js"></script>
<script src="~/Scripts/angular/angular-route.min.js"></script>
<script src="~/Scripts/angular/angular-translate-storage-cookie.min.js"></script>
<script src="~/Scripts/angular/angular-translate-storage-local.min.js"></script>
</head>
<body ng-controller="Ctrl">
<!-- Here is the html for the navigation bar etc. -->
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
I am really not an expert on AngularJS as I only wanted to provide some cool translation feature, but I hope you guys have an idea why it doesn't work in the partial views.
Its just that you need to call the partial view using ng-include("'controller/action'"). Apostrophe(') is important while writing url.
Example
<div id="TestDiv" ng-include="templateUrl"></div>
and inside the angular controller
var app = angular.module("Layout", []);
app.controller("LoadPage", function ($scope, $http, $sce) {
//Initially
$scope.templateUrl = '/Home/DefaultPage';
// To dynamically change the URL.
$scope.NewProjFn = function () {
$scope.templateUrl = '/Home/ProjectPage';
};
});
It might well not at all be difficult for you to re-implement it but by using ng-include you also need not to make an ajax call. It do it all by itself which includes ajax call, compilation and display. But the functions like ng-click and other events will not work as its a one time compilation process.

Breezejs flips the EntityState from Added to Modified before Save

I am building a SPA per the guidance provided in John Papa's Jumpstart.
When I create the model, it has
modelObservable().entityAspect.entityState.isAdded() = true;
I update the text, dropdown and
modelObservable().entityAspect.entityState.isAdded() = false;
in my Datacontext:
var createProject = function (position) {
return manager.createEntity(entityNames.project,
{
positionId : position.id(),
start : position.start(),
memberId : position.memberId()
});
};
which is called from my add viewModel:
define(['services/datacontext', 'durandal/plugins/router', 'durandal/system', 'durandal/app', 'services/logger', 'services/uiService'],
function (datacontext, router, system, app, logger, ui) {
var model = ko.observable();
var position = ko.observable();
var hourTypes = ko.observableArray([]);
var isSaving = ko.observable(false);
// init
var activate = function (routeData) {
logger.log('Add View Activated', null, 'add', true);
var positionId = parseInt(routeData.id);
initLookups();
return datacontext.getPositionById(positionId, position).then(**createProject**);
};
var initLookups = function () {
logger.log('initLookups', null, 'add', true);
hourTypes(datacontext.lookups.hourTypes);
};
// state
**var createProject = function () {
return model(datacontext.createProject(position()));
}**
var addNewProject = function () {
if (position == undefined || position().id() < 1) {
console.log('callback addNewProject');
setTimeout(function () {
addNewProject();
}, 1000);
} else {
datacontext.addProject(position(), model);
console.log(model().id());
return;
}
}
var **save** = function () {
isSaving(true);
**datacontext.saveChanges()**
.then(goToEditView).fin(complete);
function complete() {
isSaving(false);
}
function goToEditView() {
isSaving(false);
var url = '#/Projects/';
router.navigateTo(url + model().id());
}
};
var vm = {
activate: activate,
hourTypes: hourTypes,
isAdded: isAdded,
model: model,
save: save,
title: 'Details View'
};
return vm;
});
the html
<section data-bind="with:model">
<h1 data-bind="text: name"> <i class="icon-asterisk" data-bind="visible: hasChanges" style="font-size: 30px;"></i></h1>
<div class="errorPanel"></div>
<div id="overview" class="project" >
<div class="row">
<div class="span4">
<label class="requiredLabel">Name*</label>
<input type="text" name="name" data-bind="value: name" style="width: 27em;" class="required" placeholder="Project Name" required validationMessage="Project Name required" /><span class="k-invalid-msg" data-for="title"></span>
</div>
</div>
<div class="row">
<div class="span3"><label class="requiredLabel">Start*</label></div>
<div class="span3"><label class="requiredLabel">End</label></div>
</div>
<div class="row">
<div class="span3"><input name="start" data-bind="shortDate: start" class="date required" required="required" placeholder="mm/dd/yyyy" style=" width:142px"></div>
<div class="span3"><input name="end" data-bind="shortDate: end" class="date" placeholder="mm/dd/yyyy" style=" width:142px"><span class="k-invalid-msg" data-for="end"></span></div>
</div>
<br/>
<div class="row">
<div class="span3"><label for="hourType" class="requiredLabel">Measure As*</label></div>
<div class="span2"><label for="hoursPerWeek" class="requiredLabel">Hours/Week</label></div>
<div class="span2"><label for="totalHours" class="requiredLabel">Total Hours</label></div>
</div>
<div class="row">
<div class="span3">
<select id="hourType" data-bind="options: $parent.hourTypes, optionsText: 'name', value: hourType" required validationMessage="Measure As required"></select><span class="k-invalid-msg" data-for="hourType"></span>
</div>
<div class="span2">
<input name="hoursPerWeek" type="number" min="1" max="120" required="required" data-bind="value: hoursPerWeek, validationOptions: { errorElementClass: 'input-validation-error' }, enable: hourType().id() == 1" class="hours required"" style="width: 80px;" validationMessage="Hours required"><span class="k-invalid-msg" data-for="projectHours"></span>
<span class="k-invalid-msg" data-for="totalHours"></span>
</div>
<div class="span2">
<input name="totalHours" type="number" min="40" max="2080" required="required" data-bind="value: totalHours, validationOptions: { errorElementClass: 'input-validation-error' }, enable: hourType().id() == 2" class="hours required"" style="width: 80px;" validationMessage="Hours required"><span class="k-invalid-msg" data-for="projectHours"></span>
<span class="k-invalid-msg" data-for="totalHours"></span>
</div>
</div>
<div class="row">
<div class="span4">
<label class="requiredLabel">Description*</label><span class="k-invalid-msg" data-for="description"></span><span id="posMinDesc" style="visibility:hidden"></span>
<textarea id="description" name="description" style="height: 200px; width: 650px;" data-bind="value: description, enabled:true, click: $parent.clearDefaults" rows="4" cols="60" class="richTextEditor k-textbox" required validationMessage="Description required" ></textarea>
</div>
</div>
</div>
<div class="button-bar">
<button class="btn btn-info" data-bind="click: $parent.goBack"><i class="icon-hand-left"></i> Back</button>
<button class="btn btn-info" data-bind="click: $parent.save, enable: $parent.canSave"><i class="icon-save"></i> Save</button>
</div>
</section>
The json breeze sends to my controller is this:
{
"entities": [
{
"Id": -1,
"Description": "poi",
"End": null,
"Gauge": 0,
"Score": 0,
"HourTypeId": 1,
"HoursPerWeek": 45,
"HourlyRate": null,
"TotalHours": null,
"WeightedHours": 0,
"CreditMinutes": 0,
"TotalCompensation": null,
"IsCurrent": false,
"Name": "poi",
"PositionId": 1,
"MemberId": 1,
"Start": "2011-09-01T00:00:00Z",
"undefined": false,
"entityAspect": {
"entityTypeName": "Project:#SkillTraxx.Model",
"defaultResourceName": "Projects",
"entityState": "Modified",
"originalValuesMap": {
"Name": "",
"HourTypeId": 0,
"HoursPerWeek": null,
"Description": ""
},
"autoGeneratedKey": {
"propertyName": "Id",
"autoGeneratedKeyType": "Identity"
}
}
}
],
"saveOptions": {}
}
As you can see, the above is incorrect b/c state is "Modified" and the Id = -1. This throws an error server side. I suppose I could trap the DbUpdateConcurrencyException, unwind the JObject and change "Modified" to added, but that's got code smell all over it.
If anyone can help me find the face-palm moment in all of this, I'm ready.
Thanks for looking!
FACE PALMED IT
I took Jays advice and started stripping away the html then I realize it was my handler.
The update method on shortDate handler was responsible. I wrapped it in an if statement not to send the update if the current state is added.
ko.bindingHandlers.shortDate = {
init: function (element, valueAccessor) {
//attach an event handler to our dom element to handle user input
element.onchange = function () {
var value = valueAccessor();//get our observable
//set our observable to the parsed date from the input
value(moment(element.value).toDate());
};
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
if (valueUnwrapped) {
element.value = moment(valueUnwrapped).format('L');
if (!viewModel.entityAspect.entityState.isAdded())
{
**viewModel.entityAspect.setModified();**
}
}
}
};

entityAspect.setDeleted doesn't fire the subscribed propertyChanged event

I am running into problem where i subscribe to propertyChanged event, the subscribed event does fire for entity Modification, but never fires for when setting entity to Deleted.
what might i be doing wrong.
The objective of what i am doing is that, whenever user modifies the row, i want to provide
button at row level to cancel the changes. similarly when user deletes a row, i want to provide a button to unDelete a row. The modification part works as expected, but for Delete it is not working.
I was Expecting that item.entityAspect.setDeleted(), would fire the propertyChanged Event
so that i can update the vlaue of observable IsDeleted,which in turn would update the visibility of the button.
ViewModel
/// <reference path="jquery-1.8.3.js" />
/// <reference path="../linq-vsdoc.js" />
/// <reference path="../linq.min.js" />
/// <reference path="../breeze.intellisense.js" />
/// <reference path="../breeze.debug.js" />
$(document).ready(function () {
//extend country type
var Country = function () {
console.log("Country initialized");
var self = this;
self.Country_ID = ko.observable(0); // default FirstName
self.Country_Code = ko.observable(""); // default LastName
self.Country_Name = ko.observable("");
self.entityState = ko.observable("");
self.hasValidationErrors = ko.observable(false);
self.IsDeleted = ko.observable(false);
self.IsModified = ko.observable(false);
self.templateName = ko.observable("AlwayEditable");
var onChange = function () {
var hasError = self.entityAspect.getValidationErrors().length > 0;
if (hasError)
self.hasValidationErrors(true);
else
self.hasValidationErrors(false);
};
//dummy property to wireup event
//should not be used for any other purpose
self.hasError = ko.computed(
{
read: function () {
self.entityAspect // ... and when errors collection changes
.validationErrorsChanged.subscribe(onChange);
},
// required because entityAspect property will not be available till Query
// return some data
deferEvaluation: true
});
//dummy property to wireupEvent and updated self.entityStateChanged property
self.entityStateChanged = ko.computed({
read: function () {
self.entityAspect.propertyChanged.subscribe(function (changeArgs) {
if (changeArgs.entity.entityAspect.entityState.name == "Deleted") {
self.IsDeleted(false);
}
else if (changeArgs.entity.entityAspect.entityState.name == "Modified")
self.IsModified(true);
}); //subscribe
},
deferEvaluation: true,
// self.entityStateChanged(false)
});
self.fullName = ko.computed(
function () {
return self.Country_Code() + " --- " + self.Country_Name();
});
};
manager.metadataStore.registerEntityTypeCtor("Country", Country);
var countryViewModel = function (manager) {
var self = this;
window.viewModel = self;
self.list = ko.observableArray([]);
self.pageSize = ko.observable(2);
self.pageIndex = ko.observable(0);
self.selectedItem = ko.observable();
self.hasChanges = ko.observable(false);
self.totalRows = ko.observable(0);
self.totalServerRows = ko.observable(0);
self.RowsModified = ko.observable(false);
self.RowsAdded = ko.observable(false);
self.RowsDeleted = ko.observable(false);
self.templateToUse = function (dataItem, context) {
var item = dataItem;
if (!_itemTemplate) {
_itemTemplate = ko.computed(function (item) {
//var x = this;
if (this.entityAspect == "undefined")
return this.templateName("AlwayEditable");
if (this.entityAspect.entityState.name == "Deleted") {
this.templateName("readOnlyTmpl");
return this.templateName();
}
else {
this.templateName("AlwayEditable");
return this.templateName();
}
}, item);
}
if (item.entityAspect.entityState.name == "Deleted") {
item.templateName("readOnlyTmpl");
return item.templateName();
}
else {
item.templateName("AlwayEditable");
return item.templateName();
}
// return _itemTemplate();
}
var _itemTemplate;
self.hasError = ko.computed(
{
read: function () {
self.entityAspect // ... and when errors collection changes
.validationErrorsChanged.subscribe(onChange);
},
// required because entityAspect property will not be available till Query
// return some data
deferEvaluation: true
});
self.acceptChanges = function (item) {
// self.selectedItem().entityAspect.acceptChanges();
self.selectedItem(null);
}
manager.hasChanges.subscribe(function (newvalue) {
self.hasChanges(newvalue.hasChanges);
});
self.edit = function (item, element) {
highlightRow(element.currentTarget, item);
self.selectedItem(item);
};
self.discardChanges = function () {
manager.rejectChanges();
manager.clear();
self.pageIndex(0);
self.loadData();
};
self.cancel = function (item, element) {
item.entityAspect.rejectChanges();
self.selectedItem(null);
};
self.add = function () {
var countryType = manager.metadataStore.getEntityType("Country"); // [1]
var newCountry = countryType.createEntity(); // [2]
//if not using this line, the table is not updated to show this newly added item
self.list.push(newCountry);
manager.addEntity(newCountry); // [3]
self.selectedItem(newCountry);
};
self.remove = function (item) {
item.entityAspect.rejectChanges();
item.entityAspect.setDeleted(); //was expecting that propertychaged subscribe event will fire, but it does not
item.templateName("readOnlyTmpl"); //if i don't do this the template is not changed/updated
item.IsDeleted(true); //have to use this
};
self.UndoDelete = function (item) {
item.entityAspect.rejectChanges();
item.templateName("AlwayEditable");
item.IsDeleted(false);
};
self.save = function () {
if (manager.hasChanges()) {
alertTimerId = setTimeout(function () {
//this works as well
$.blockUI({ message: '<img src="Images/360.gif" /> </p><h1>Please Saving Changes</h1>', css: { width: '275px' } });
}, 700);
manager.saveChanges()
.then(saveSucceeded(alertTimerId))
.fail(saveFailed);
} else {
$.pnotify({
title: 'Save Changes',
text: "Nothing to save"
});
// alert("Nothing to save");
};
};
manager.hasChanges.subscribe(function (newvalue) {
self.hasChanges(newvalue.hasChanges);
});
manager.entityChanged.subscribe(function (changeArg) {
self.RowsDeleted(manager.getEntities(null, [breeze.EntityState.Deleted]).length);
self.RowsModified(manager.getEntities(null, [breeze.EntityState.Modified]).length);
self.RowsAdded(manager.getEntities(null, [breeze.EntityState.Added]).length);
});
//we want maxPageIndex to be recalculated as soon as totalRows or pageSize changes
self.maxPageIndex = ko.dependentObservable(function () {
return Math.ceil(self.totalRows() / self.pageSize()) - 1;
//return Math.ceil(self.list().length / self.pageSize()) - 1;
});
self.previousPage = function () {
if (self.pageIndex() > 1) {
self.pageIndex(self.pageIndex() - 1);
//self.loadData();
getData();
}
};
self.nextPage = function () {
if (self.pageIndex() < self.maxPageIndex()) {
self.pageIndex(self.pageIndex() + 1);
// self.loadData();
getData();
}
};
self.allPages = ko.dependentObservable(function () {
var pages = [];
for (i = 0; i <= self.maxPageIndex() ; i++) {
pages.push({ pageNumber: (i + 1) });
}
return pages;
});
self.moveToPage = function (index) {
self.pageIndex(index);
//self.loadData();
getData();
};
};
// self.loadData
var vm = new countryViewModel(manager);
//ko.validation.group(vm);
ko.applyBindings(vm);
// ko.applyBindingsWithValidation(vm);
vm.loadData();
try {
} catch (e) {
displayModalMessage("Page Error :- Reload the Page", e.message);
}
}); //end document.ready
View
<p><a class="btn btn-primary" data-bind="click: $root.add" href="#" title="Add New Country"><i class="icon-plus"></i> Add Country</a></p>
<span> Search Country Code :</span><input id="txtSearch" type="text" /><input id="BtnSearch" type="button" value="Search" data-bind="click: $root.loadData" />
<!--<table class="table table-striped table-bordered " style="width: 700px">-->
<!--<table id="myTable" class="ui-widget" style="width: 800px">-->
<table id="myTable" class="table table-striped table-bordered " style="width: 1200px">
<caption> <div>
<span class="label label-info">Number of Rows Added </span> <span class="badge badge-info" data-bind="text: RowsAdded"></span> ,
<span class="label label-success">Number of Rows Modified</span> <span class="badge badge-success" data-bind="text: RowsModified"></span> ,
<span class="label label-important">Number of Rows Deleted</span> <span class="badge badge-important" data-bind="text: RowsDeleted"></span>
<p/>
</div></caption>
<thead class="ui-widget-header">
<tr>
<th>Code</th>
<th>Name</th>
<th>Full Name</th>
<th />
</tr>
</thead>
<!--<tbody data-bind=" title:ko.computed(function() { debugger; }), template:{name:templateToUse, foreach: list, afterRender: HighlightRows }" class="ui-widget-content"></tbody>-->
<tbody data-bind=" title:ko.computed(function() { debugger; }), template:{name:templateToUse, foreach: list}" ></tbody>
</table>
<div class="pagination">
<ul><li data-bind="css: { disabled: pageIndex() === 0 }">Previous</li></ul>
<ul data-bind="foreach: allPages">
<li data-bind="css: { active: $data.pageNumber === ($root.pageIndex() + 1) }"></li>
</ul>
<ul><li data-bind="css: { disabled: pageIndex() === maxPageIndex() }">Next</li></ul>
</div>
<!--<input id="Button1" type="button" value="Save" data-bind="attr: { disabled: !hasChanges()}, click:saveChanges" />-->
<a class="btn btn-success btn-primary" data-bind="click: $root.save, css: { disabled: !$root.hasChanges()}" href="#" title="Save Changes"> Save Changes</a>
<!-- <input id="Button3" type="button" value="Create New" data-bind="click:AddNewCountry" />
<input id="Button4" type="button" value="Discard and reload data" data-bind="click:discardreload, attr: { disabled: !hasChanges()}" /> -->
<a class="btn btn-danger btn-primary" data-bind="click: $root.discardChanges, css: { disabled: !$root.hasChanges()}" href="#" title="Discard Changes"><i class="icon-refresh"></i> Discard & Reload</a>
<script id="readOnlyTmpl" type="text/html">
<tr >
<td>
<span class="label " data-bind="text: Country_Code "></span>
<div data-bind="if: hasValidationErrors">
<span class="label label-important" data-bind="text: $data.entityAspect.getValidationErrors('Country_Code')[0].errorMessage ">Important</span>
</div>
</td>
<td>
<span class="label " data-bind="text: Country_Name "></span>
<p data-bind="validationMessage: Country_Name"></p>
<span data-bind='visible: ko.computed(function() { debugger; }), text: Country_Name.validationMessage'> </span>
</td>
<td> <span class="label " data-bind="text: fullName "></span>
</td>
<td >
<a class="btn btn-danger" data-bind="click: $root.cancel, visible: $data.IsModified" href="#" title="cancel/undo changes">Undo Changes<i class="icon-trash"></i></a>
<a class="btn btn-danger" data-bind="click: $root.remove, visible: !$data.IsDeleted() " href="#" title="Delete this Row">Delete<i class="icon-remove"></i></a>
<a class="btn btn-danger" data-bind="click: $root.UndoDelete, visible: $data.IsDeleted() " href="#" title="Undo Delete">Un Delete<i class="icon-remove"></i></a>
</td>
</tr>
</script>
<script id="AlwayEditable" type="text/html">
<tr >
<td><input type="text" placeholder="Country Code" data-bind="value: Country_Code , uniqueName: true, css: { error: hasValidationErrors }, valueUpdate: 'afterkeydown'"/>
<!-- <div data-bind="if: $data.entityAspect.getValidationErrors().length>0">
<pre data-bind="text: $data.entityAspect.getValidationErrors('Country_Code')[0].errorMessage "></pre>
</div>-->
<div data-bind="if: hasValidationErrors">
<span class="label label-important" data-bind="text: $data.entityAspect.getValidationErrors('Country_Code')[0].errorMessage ">Important</span>
</div>
</td>
<td><input type="text" placeholder="Country Name" data-bind="value: Country_Name, uniqueName: true, valueUpdate: 'afterkeydown'"/>
<p data-bind="validationMessage: Country_Name"></p>
<span data-bind='visible: ko.computed(function() { debugger; }), text: Country_Name.validationMessage'> </span>
</td>
<td>
<span data-bind=' text: fullName'> </span>
</td>
<td >
<a class="btn btn-danger" data-bind="click: $root.cancel, visible: $data.IsModified" href="#" title="cancel/undo changes">Undo Changes<i class="icon-trash"></i></a>
<a class="btn btn-danger" data-bind="click: $root.remove, visible: !$data.IsDeleted() " href="#" title="Delete this Row">Delete<i class="icon-remove"></i></a>
<a class="btn btn-danger" data-bind="click: $root.UndoDelete, visible: $data.IsDeleted() " href="#" title="Undo Delete">Un Delete<i class="icon-remove"></i></a>
</td>
</tr>
</script>
Analysis
The propertyChanged event is raised when ... a property changes. But that's not what you want to watch. You want to monitor the entityAspect.entityState
When you set a property to a new value (for example person.FirstName("Naunihal")), you get both a propertyChanged event and a change to the entity's EntityState.
When you delete the entity, the entity's EntityState changes ... to "Deleted". But deleting doesn't change a property of the entity. Breeze does not consider the EntityState itself to be a property of the entity. Therefore, there is no propertyChanged notification.
Solution
Update Jan 12, 2013
I think more people will discover this solution if I rephrase the question that you asked so people understand that you want to listen for changes to EntityState.
So I moved my answer to a new SO question: "How can I detect a change to an entity's EntityState?". Hope you don't mind following that link.

Resources