Eric lippert - Amazon Web Services
Eric lippert - Amazon Web Services
Eric lippert - Amazon Web Services
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
$(document).ready(function ()<br />
{<br />
$.ajax({<br />
url: “/api/TimeCard”,<br />
method: “GET”,<br />
contentType: “text/json”,<br />
success: function (data)<br />
{<br />
viewModel.timecards.removeAll();<br />
$.each(data, function (index)<br />
{<br />
viewModel.timecards.push(addNewTimeCard(<br />
data[index]));<br />
});<br />
ko.applyBindings(viewModel);<br />
}<br />
});<br />
Once the document loads, we call the server to get all the time<br />
cards available. When the server returns the data, we add each<br />
TimeCard to the view model. Since the ‘timecards’ property is a<br />
KO Observable, Knockout will automatically update the view as<br />
each timecard is added.<br />
$(document).delegate(“#submitButton”, “click”, function<br />
()<br />
{<br />
viewModel.commitAll();<br />
var vm = viewModel.selectedTimeCard;<br />
var current = ko.utils.unwrapObservable(vm);<br />
var stringyF = JSON.stringify(ko.mapping.<br />
toJS(current));<br />
var action = “PUT”;<br />
var vUrl = “/api/TimeCardId=” + current.Id();<br />
if (current.Id()==0)<br />
{<br />
action = “POST”;<br />
vUrl = “/api/TimeCard”;<br />
}<br />
$.ajax(<br />
{<br />
url: vUrl,<br />
contentType: “application/json;charset=utf-8”,<br />
type: action,<br />
data: stringyF,<br />
success: function (response)<br />
{<br />
alert(“Saved Successfully”);<br />
viewModel.selectedTimeCard(null);<br />
},<br />
failure: function (response)<br />
{<br />
alert(“Save Failed”);<br />
}<br />
});<br />
});<br />
The Submit button click handler has the implementation for<br />
sending the currently selected TimeCard’s information to be<br />
saved in the Server.<br />
To do this, the ‘selectedTimeCard’ object is converted into a JSON<br />
string and put in the payload of the Ajax POST.<br />
$(document).delegate(“#cancelButton”, “click”, function<br />
()<br />
{<br />
viewModel.selectedTimeCard(null);<br />
});<br />
Cancelling the Edit process simply resets the selectedTimeCard<br />
property to null. This hides the Edit Panel on the UI.<br />
Running the App to Get and Put/<br />
Post data to <strong>Web</strong> API<br />
Now that we have our <strong>Web</strong> API Controller and Index.cshtml with<br />
its client side dependencies setup, let’s run the app. On first run,<br />
we are greeted with a near empty screen with only the ‘Add New<br />
TimeCard’ button and the list headers for the TimeCards<br />
Clicking on ‘Add New TimeCard’ adds a default time card<br />
DNcmagazine www.dotnetcurry.com | 67