I am writing CRUD application using ASP.NET MVC,KnockoutJS and database. When i write separate viewmodel for Create, Read, Update and Delete.and calling each viewmodel in separate view (Create, Read, Update and Delete) then It's working fine. But when i include all viewmodel in one single viewmodel then calling that viewmodel in every View. Then i am neither able to create not able to edit.
Please help me with this. I tried so many ways but could not get proper solution.
What I have tried:
I have written this function using Knockout:
$(function () {
ko.applyBindings(modelView);
});
var parsedSelectedCourse = $.parseJSON(selectedCourse);
var modelView = {
Read: {
Courses: ko.observableArray([]),
viewCourses: function () {
var thisObj = this;
try {
$.ajax({
url: '/Home/ListCourses',
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
thisObj.Courses(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Create: {
CourseName: ko.observable(),
CourseDescription: ko.observable(),
createCourse: function () {
try {
$.ajax({
url: '/Home/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Update: {
CourseID: ko.observable(parsedSelectedCourse.CourseID),
CourseName: ko.observable(parsedSelectedCourse.CourseName),
CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
updateCourse: function () {
try {
$.ajax({
url: '/Home/Update',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Delete: {
CourseID: ko.observable(parsedSelectedCourse.CourseID),
CourseName: ko.observable(parsedSelectedCourse.CourseName),
CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
deleteCourse: function () {
try {
$.ajax({
url: '/Home/Delete',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
}
};
function successCallback(data) {
window.location.href = '/Home/Read/';
}
function errorCallback(err) {
window.location.href = '/Home/Read/';
}
Please help me with an idea. Thanks