Knockout asp.net - cannot read property of undefined - asp.net

I'm really new to Knockout and have a question:
I try this example from the officail site.
So my html file is:
<head>
<script src="Scripts/jquery-2.1.1.min.js"></script>
<script src="Scripts/knockout-3.2.0.js"></script>
</head>
<body>
<div data-bind='simpleGrid: gridViewModel'> </div>
<button data-bind='click: addItem'>
Add item
</button>
<button data-bind='click: sortByName'>
Sort by name
</button>
<button data-bind='click: jumpToFirstPage, enable: gridViewModel.currentPageIndex'>
Jump to first page
</button>
<script src="FuseJS.js"></script>
</body>
</html>
and my js file is:
/// <reference path="Scripts/jquery-2.1.1.min.js" />
/// <reference path="Scripts/knockout-3.2.0.js" />
var initialData = [
{ name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
{ name: "Speedy Coyote", sales: 89, price: 190.00 },
];
var PagedGridModel = function (items) {
this.items = ko.observableArray(items);
this.addItem = function () {
this.items.push({ name: "New item", sales: 0, price: 100 });
};
this.sortByName = function () {
this.items.sort(function (a, b) {
return a.name < b.name ? -1 : 1;
});
};
this.jumpToFirstPage = function () {
this.gridViewModel.currentPageIndex(0);
};
this.gridViewModel = new ko.simpleGrid.viewModel({
data: this.items,
columns: [
{ headerText: "Item Name", rowText: "name" },
{ headerText: "Sales Count", rowText: "sales" },
{ headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } }
],
pageSize: 4
});
};
ko.applyBindings(new PagedGridModel(initialData));
What am I missing? I debug the code I saw this error
"UncauchType error: cannot read property 'viewModel' of undefined"
tnx

You are not using ko.applyBindings() anywhere.
ideally you need to do something like this.
ko.applyBindings(new PagedGridModel(initialData));

Related

Need to transform Razor code on ASPX code

So, I need help to make this code work as ASPX, can anyone help me?
I know it,s just a few parts to be changed, but i don't know how to do it...
Or if Any one know hot to achive the same result other way this would be very helpfull.
I already try do it myself but got no luck doing so.. =/
So, I need help to make this code work as ASPX, can anyone help me?
I know it,s just a few parts to be changed, but i don't know how to do it...
Or if Any one know hot to achive the same result other way this would be very helpfull.
I already try do it myself but got no luck doing so.. =/
#{
ViewBag.Title = "Employee List";
}
<a class="btn btn-success" style="margin-bottom:10px"
onclick="PopupForm('#Url.Action("AddOrEdit","Employee")')"><i class="fa fa-
plus"></i> Add New</a>
<table id="employeeTable" class="table table-striped table-bordered"
style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
<th></th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
#section scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#employeeTable").DataTable({
"ajax": {
"url": "/Employee/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name" },
{ "data": "Position" },
{ "data": "Office" },
{ "data": "Age" },
{ "data": "Salary" },
{"data":"EmployeeID" , "render" : function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit","Employee")/" + data + "')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete("+data+")><i class='fa fa-trash'></i> Delete</a>";
},
"orderable": false,
"searchable":false,
"width":"150px"
}
],
"language": {
"emptyTable" : "No data found, Please click on <b>Add New</b> Button"
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: 'Fill Employee Details',
height: 500,
width: 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if($(form).valid()){
$.ajax({
type : "POST",
url : form.action,
data : $(form).serialize(),
success : function (data) {
if(data.success)
{
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,{
globalPosition :"top center",
className : "success"
})
}
}
});
}
return false;
}
function Delete(id) {
if(confirm('Are You Sure to Delete this Employee Record ?'))
{
$.ajax({
type: "POST",
url: '#Url.Action("Delete","Employee")/' + id,
success: function (data) {
if (data.success)
{
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
}
</script>
}

Vue-Full-Calendar refetch-events error

I am having issues refreshing events when I add a new one. The event gets inserted into the database fine, but the call to
this.$refs.calendar.$emit('refetch-events')
Throws the following error:
[Vue warn]: Error in event handler for "refetch-events": "TypeError: $(...).fullCalendar is not a function"
Here is some more of the code to further demonstrate what I am trying to do:
<template>
<div>
<full-calendar ref="calendar" :event-sources="eventSources" #day-click="daySelected" #event-selected="eventSelected" :config="config"></full-calendar>
<!-- Modal Component -->
<b-modal ref="my_modal" title="New Appointment" #ok="submit" #shown="clearModalValues">
<form #submit.stop.prevent="submit">
<label>Client:</label>
<b-form-select v-model="selectedClient" :options="clientOptions" class='mb-3'></b-form-select>
<label>Service:</label>
<b-form-select multiple v-model="selectedService" :options="serviceOptions" class='mb-3'></b-form-select>
<label>Start time:</label>
<time-picker v-model="myTime"></time-picker>
<label>Notes:</label>
<b-form-input textarea v-model="notes" placeholder="Notes"></b-form-input>
</form>
</b-modal>
<!-- /Modal Component -->
</div>
</template>
<script>
export default {
props: {
staff:{
type: Number,
required: true
},
},
data() {
return {
myTime: new Date(),
selectedService: [null],
selectedClient: null,
selectedStartTime: new Date(),
notes: null,
serviceOptions: [],
clientOptions: [],
events: [],
config: {
timeFormat: 'h(:mm)',
eventClick: (event) => {
console.log('Event Clicked: '+event.title);
},
},
selected: {},
};
},
computed: {
eventSources() {
return [
{
events(start, end, timezone, callback) {
axios.get('/getEvents').then(response => {
callback(response.data)
})
}
}
]
}
},
mounted() {
this.myTime = new Date()
axios.get('/getClients').then(response => this.clientOptions = response.data);
axios.get('/getServices').then(response => this.serviceOptions = response.data);
},
methods: {
clearModalValues() {
this.selectedService = [null];
this.selectedClient = null;
this.selectedStartTime = new Date();
this.myTime = new Date();
this.notes = null;
},
submit(e) {
axios.post('/addEvent/',{'selectedService':this.selectedService,'selectedClient':this.selectedClient,'selectedStartTime':this.selectedStartTime,'notes':this.notes}).then(function(response){
//console.log(response.data);
new PNotify({
title: 'Success',
text: 'New event has been created',
icon: 'icon-checkmark3',
type: 'success'
});
this.selectedService = [null];
this.selectedClient = null;
this.selectedStartTime = new Date();
this.notes = null;
this.myTime = new Date();
// ******** I HAVE TRIED THESE CALLS AS PER DOCUMENTATION **********
//this.$refs.calendar.fireMethod('refetch-events')
//this.$refs.calendar.fullCalendar.$emit('refetch-events');
//this.$refs.calendar.$emit('refetch-events');
console.log(this.$refs.calendar);
}.bind(this));
},
eventSelected(event) {
console.log('Event Selected: '+event.title);
},
daySelected(date,event,view){
this.$refs.my_modal.show();
this.selectedStartTime = date.format("YYYY-MM-DD HH:mm:ss");
this.myTime = date.toDate();
},
},
};
</script>
According to the documentation it should be correct. I know its late and I have been at this for a couple hours so I might be overlooking something simple. Again this is vue-full-calendar and not regular full-calendar. I just need to call refetchEvents when I add the new events in the submit method. Thanks!
I have found the issue, thanks to Brock for the help. I had multiple versions of jquery running(the html template I was using was also calling it).

How to get all checkbox props with React + ASP.net mvc

I am learning React and ASP.net( not core).
I try to create a small project for practice.
I have a number of checkboxes and a submit button.
The idea is when I click on the button I want to create a Jason that will contain a list of the checkboxes text and their states (check \uncheck).
That Jason I want to send to the server.
I mange to create the components and the relevant events.
But fail to create the following
1) Get the state of the checkbox from the submit component and create a Jason out of it.
2) Send that Jason to the server side (ASP.net).
I try to flow the tutorial but didn’t get it, I tried to find solution on the internet but with no lack.
If someone can show me how to do it – or give me some direction that will help
Thanks
the jsk:
var data = [
{ Id: 1, ActionItem: "Action1" },
{ Id: 2, ActionItem: "Action2" },
{ Id: 3, ActionItem: "Action3" }
];
var Checkbox = React.createClass({
getInitialState: function() {
return {
isChecked: false
};
},
toggleChange: function() {
this.setState({
isChecked: !this.state.isChecked
},
function() {
console.log(this.state);
}.bind(this));
},
render: function() {
return (
<label>
<input type="checkbox"
checked={this.state.isChecked}
onChange={this.toggleChange} />{this.props.chkboxlabel}<br />
</label>
);
}
});
var ActionBox = React.createClass({
render: function() {
return (
<div className="actionBox">
<h1>Select Action </h1>
<CheckboxList data={this.props.data} />
<SubmitForm/>
</div>
);
}
});
var CheckboxList = React.createClass({
render: function() {
var actionNodes = this.props.data.map(function(action) {
return (
<Checkbox chkboxlabel={action.ActionItem} key={action.id}>
{action.ActionItem}
</Checkbox>
);
});
return (
<form className="actionList">{actionNodes}
</form>
);
}
});
var SubmitForm = React.createClass({
handleSubmit: function(e) {
//??
},
render: function() {
return (
<form className="actionForm" onSubmit={this.handleSubmit}>
<input type="submit" value="Run" />
</form>
);
}
});
ReactDOM.render(
<ActionBox data={data} />,
document.getElementById('content')
);
I found a solution that works I don’t think it’s the best way but maybe it will help other.
I loop thought the element to get the value- I believe there is a better way of doing it with react.
var data = [
{ Label: "Action 1", IsChecked: false, Name: "a1" },
{ Label: "Action 2", IsChecked: false, Name: "a2" },
{ Label: "Action 3", IsChecked: false, Name: "a3" }
];
handleCommentSubmit: function () {
var data = new FormData();
var inputs = document.getElementsByName('mycheckbox');
for (var i = 0; i < inputs.length; i++) {
var name = inputs.item(i).value;
var ischecked = inputs.item(i).checked;
data.append(name, ischecked);
}
var xhr = new XMLHttpRequest();
xhr.open('post', this.props.submitUrl, true);
xhr.send(data);
},

display:none is not freeing up the space in firefox

I am using react.js for displaying some data. I have more than one divs one below other. and each div contain graph, created from chart.js. I have one button in every div to display or hide that particular chart. It is working nicely. But when I hide that graph, my firefox is still not freeing up the space which was taken by chart when it was getting displayed. Like when I am hiding my chart, the space is getting created between two divs. The code is working properly in Microsoft Edge browser.
Here is my code:
var Div= React.createClass({
getInitialState: function () {
return {
displayChart: false
};
},
chartClick: function () {
this.setState({
displayChart: !this.state.displayChart,
});
},
render: function() {
return (
<div>
<p className="text-justify">
{ this.props.detail }
</p>
<button type="button" className="btn btn-link" onClick={ this.chartClick }>Chart</button>
{ this.state.displayChart ?
<ChartGraph id={this.props.id} />
: null }
</div>
);
}
});
Chart Component is :
ChartGraph = React.createClass({
onLoad: function () {
var barChartData = {
labels: [ option1, option2 ],
datasets: [
{
data: [451, 145],
fillColor: "rgba(46,145,202,0.8)",
strokeColor: "rgba(46,145,202,0.8)",
highlightFill: "rgba(46,145,202,1)",
highlightStroke: "rgba(46,145,202,1)"
}
]
};
var ctx = document.getElementById("canvas_poll"+this.props.id).getContext("2d")
new Chart(ctx).HorizontalBar(barChartData, {
scaleGridLineWidth: 1,
scaleShowGridLines: false,
scaleStartValue : 0
});
},
componentDidMount: function() {
this.onLoad();
},
render: function () {
return (
<div className="red">
<canvas id={"canvas_poll"+this.props.id} height="100" width="400"></canvas>
</div>
);
}
});
Any help for this problem?
Thank you..
This should work.
var Div= React.createClass({
getInitialState: function () {
return {
displayChart: false
};
},
chartClick: function () {
this.setState({
displayChart: !this.state.displayChart,
});
},
render: function() {
var hideChart = this.state.displayChart ? false : true;
return (
<div>
<p className="text-justify">
{ this.props.detail }
</p>
<button type="button" className="btn btn-link" onClick={ this.chartClick }>Chart</button>
<ChartGraph id={this.props.id} hide={hideChart} />
</div>
);
}
});
and
ChartGraph = React.createClass({
onLoad: function () {
var barChartData = {
labels: [ option1, option2 ],
datasets: [
{
data: [451, 145],
fillColor: "rgba(46,145,202,0.8)",
strokeColor: "rgba(46,145,202,0.8)",
highlightFill: "rgba(46,145,202,1)",
highlightStroke: "rgba(46,145,202,1)"
}
]
};
var ctx = document.getElementById("canvas_poll"+this.props.id).getContext("2d")
new Chart(ctx).HorizontalBar(barChartData, {
scaleGridLineWidth: 1,
scaleShowGridLines: false,
scaleStartValue : 0
});
},
componentDidMount: function() {
this.onLoad();
},
render: function () {
if (this.props.hide) return null;
return (
<div className="red">
<canvas id={"canvas_poll"+this.props.id} height="100" width="400"></canvas>
</div>
);
}
});

Update function returns an error

This code returns an "Error: $scope.todoItems.update is not a function"
(in markDone function)
As I can see in console, $scope.todoItems has functions like save(), remove() but not an update() function, but as I can see here I writing it right.
Is something that I doing is wrong? More information would be helpful?
TodoItems = new Mongo.Collection('todoItems');
if(Meteor.isClient){
angular.module('todo_am', ['angular-meteor']);
angular.module('todo_am').controller('OutputListCtrl', ['$scope', '$meteor',
function($scope, $meteor){
$scope.todoItems = $meteor.collection(TodoItems);
$scope.remove = function(todoItem){
$scope.todoItems.remove(todoItem);
};
$scope.saveCustom = function(todoItem){
todoItem.isRead = false;
$scope.todoItems.save(todoItem);
};
$scope.markDone = function(todoItem){
console.log('>>> 4', todoItem);
console.log('>>> 5', $scope.todoItems);
$scope.todoItems.update(todoItem._id, { $set: { isRead: true }}); // <<<<<<<<< This line returns error
};
$scope.markUndone = function(todoItem){
todoItem.isRead = true;
$scope.todoItems.update(todoItem);
};
}]);
}
------------------------------ UPDATE --------------------------------
This is working:
if(Meteor.isClient){
angular.module('todo_am', ['angular-meteor']);
angular.module('todo_am').controller('OutputListCtrl', ['$scope', '$meteor',
function($scope, $meteor){
$scope.todoItems = $meteor.collection(TodoItems);
$scope.remove = function(todoItem){
$scope.todoItems.remove(todoItem);
};
$scope.saveCustom = function(todoItem){
todoItem.isRead = false;
$scope.todoItems.save(todoItem);
};
$scope.markDone = function(todoItem){
TodoItems.update({ _id: todoItem._id }, { $set: { isRead: true }});
};
$scope.markUndone = function(todoItem){
TodoItems.update({ _id: todoItem._id }, { $set: { isRead: false }});
};
}]);
}
------------------------------ UPDATE2 --------------------------------
This is whole code. I do not know if it's a right solution or not but it works.
Is there any example for update exists record in DB?
$ meteor --version
Meteor 1.1.0.2
As I can see in .meteor/versions file:
angular:angular#1.3.15_1
urigo:angular#0.8.6
index.html
<body ng-app="todo_am">
<div ng-controller="OutputListCtrl">
<div ng-include="'output-list.ng.html'"></div>
<div ng-include="'insert-new-form.ng.html'"></div>
</div>
</body>
index.ng.html
<p>Nothing</p>
insert-new-form.ng.html
<div>
<input type="text" ng-model="newTodoItem.text" />
<button ng-click="saveCustom(newTodoItem); newTodoItem='';" >Add New</button>
</div>
output-list.ng.html
<div>
<ul>
<li ng-repeat="todoItem in todoItems">
<p>
{{ todoItem.text }}
<span ng-switch on="todoItem.isRead">
<span ng-switch-when="true">
<button ng-click="markUndone(todoItem)">Mark Undone</button>
</span>
<span ng-switch-default>
<button ng-click="markDone(todoItem)">Mark Done</button>
</span>
</span>
<button ng-click="remove(todoItem)">X</button>
</p>
</li>
</ul>
</div>
app.js
TodoItems = new Mongo.Collection('todoItems');
if(Meteor.isClient){
angular.module('todo_am', ['angular-meteor']);
angular.module('todo_am').controller('OutputListCtrl', ['$scope', '$meteor',
function($scope, $meteor){
$scope.todoItems = $meteor.collection(TodoItems);
$scope.remove = function(todoItem){
$scope.todoItems.remove(todoItem);
};
$scope.saveCustom = function(todoItem){
todoItem.isRead = false;
$scope.todoItems.save(todoItem);
};
$scope.markDone = function(todoItem){
TodoItems.update({ _id: todoItem._id }, { $set: { isRead: true }});
};
$scope.markUndone = function(todoItem){
TodoItems.update({ _id: todoItem._id }, { $set: { isRead: false }});
};
}]);
}
if(Meteor.isServer){
Meteor.startup(function(){
/**
* If DB is empty, add some todoItems just for DEV purposes
*/
if (TodoItems.find().count() === 0) {
var todoItems = [
{
'text': 'First todo first todo first todo first todo first todo first todo first todo first todo first todo',
'isRead': true,
'userPosted': 'Vasia'
},
{
'text': 'Second todo item',
'isRead': false,
'userPosted': 'Fedia'
},
{
'text': 'Third todo item',
'isRead': true,
'userPosted': 'Vasia'
}
];
for (var i = 0; i < todoItems.length; i++)
TodoItems.insert({text: todoItems[i].text, isRead: todoItems[i].isRead});
}
});
}
That doesn't look like $scope.todoItems is a Meteor collection. If you look through the documentation you linked (http://docs.meteor.com/#/full/mongo_collection) - there's no reference to Meteor's Mongo Collections having a "save" method.
It looks like you're using an "Angular Meteor Collection" - http://angularjs.meteor.com/api/AngularMeteorCollection
In which case a simple call to ".save" should do it. Perhaps something like this:
$scope.markDone = function(todoItem){
todoItem.isRead = true;
$scope.todoItems.save(todoItem);
};

Resources