here my goal is to create a tree on button click one popup modal has to opent where i have to input the values and and has to store in database and as well show in the tree,and also in the context menu which node we select there also an popup modal to open and get node ,delete node and renaming has to happen
here its my controller view
public class HomeController : Controller
{
private readonly ApplicationDbContext _db;
public HomeController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
return View();
}
//[HttpPost]
//public IActionResult Index(string selectedItems)
//{
// List<TreeViewModel> items=JsonConvert.DeserializeObject<List<TreeViewModel>>(selectedItems);
// return RedirectToAction("Index");
//}
public IActionResult GetTree()
{
List<TreeViewModel> nodes = new List<TreeViewModel>();
foreach (ParentClass type in _db.parent)
{
nodes.Add(new TreeViewModel
{
id = type.Id.ToString(),
parent = "#",
text = type.ParentName
});
}
foreach (ChildClass list in _db.child)
{
nodes.Add(new TreeViewModel
{
id = list.Id.ToString(),
parent = list.parentId.ToString(),
text = list.ChildName
});
}
return Json(nodes);
}
[HttpGet]
public IActionResult Create()
{
ParentClass parent = new ParentClass();
return PartialView("_HomePartial",parent);
}
[HttpPost]
public IActionResult Create(ParentClass parent)
{
if (ModelState.IsValid)
{
_db.parent.Add(parent);
_db.SaveChanges();
return PartialView("_HomePartial", parent);
}
return RedirectToAction("Index");
}
}
and my index view where i am giving button for popup modal to insert tree node in my code it taking only parent
<div class="container" id="placeHolder">
<div class="row">
<div class="col-3">
<div class="row pt-3">
<div class="col-6">
<p class="text-primary text-light">File Structure
</p>
</div>
<div class="col-6 text-end">
<button type="button" class="btn btn-primary"
data-toggle="ajax-modal" data-bs-target="#Addnode"
data-url="#Url.Action("Create")"><i class="bi
bi-plus-square-fill"></i></button>
</div>
</div>
<div id="simpleJsTree">
</div>
</div>
<div class="col=9">
</div>
</div>
</div>
javacript for tree view
$(document).ready(function () {
$.ajax({
async: true,
type: "GET",
url: "https://localhost:44376/Home/GetTree",
dataType: "json",
success: function (json) {
createJSTree(json);
}
});
});
function createJSTree(jsondata) {
$('#simpleJsTree').jstree({
"core": {
"check_callback": true,
'data': jsondata
},
"plugins": ["contextmenu"],
"contextmenu": {
"items": function ($node) {
var tree = $("#simpleJsTree").jstree(true);
return {
"Create": {
"separator_before": false,
"separator_after": true,
"label": "Create",
"action": function (obj) {
tree.create_node($node);
}
},
"Rename": {
"separator_before": false,
"separator_after": false,
"label": "Rename",
"action": function (obj) {
tree.edit($node);
}
},
"Remove": {
"separator_before": false,
"separator_after": false,
"label": "Remove",
"action": function (obj) {
tree.delete_node($node);
}
},
"Upload": {
"seperator_beore": false,
"seperator_after": false,
"label": "Upload"
}
};
}
}
}).bind('create_node.jstree', function (e, data) {
$.ajax({
url: "/Home/Create",
method: "POST",
data: data,
success: function (data) {
console.log(data);
}
});
});
}
here binding of create function to context menu is not working
this is the partial view where i m calling modal popup to take parent node
#model ParentClass
<div class="modal fade" id="Addnode">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"id="Addnode">Add Node</h4>
<button type="button" class="close" data-bs-
dismiss="modal">
<span>X</span>
</button>
</div>
<div class="modal-body">
<form asp-controller="Home" asp-action="Create"
method="post">
#Html.HiddenFor(m=>m.Id)
<div class="form-group">
<label asp-for="ParentName"></label>
<input asp-for="ParentName"class="form-
control" />
<span asp-validation-
for="ParentName"class="text-danger"></span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"
data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary"
data-save="modal">Save</button>
</div>
</div>
</div>
</div>
and site.js file to show modal popup
$(function () {
var placeElement = $('#placeHolder');
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeElement.html(data);
placeElement.find('.modal').modal('show');
});
});
placeElement.on('click', '[data-save="modal"]', function
(event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
placeElement.find('.modal').modal('hide');
});
});
});
You are making ajax call with the codes:
var sendData = form.serialize();
$.post(actionUrl, sendData)
controller in MVC project read data from request form by default,So you need to add
[FromBody]
[HttpPost]
public IActionResult Create([FromBody]ParentClass parent)
{
_db.parent.Add(parent);
_db.SaveChanges();
return PartialView("_HomePartial", parent);
}
if you have further issue on the case,please show more details of the error
Related
So I have a dropzone file uploader. each successfull upload returns the following
File: {
"upload": {
"uuid": "f89f409b-7e49-4503-98d8-dc060e75b874",
"progress": 0,
"total": 5017004,
"bytesSent": 0,
"filename": "20190902_115950.jpg"
},
"status": "error",
"previewElement": {},
"previewTemplate": {},
"accepted": false,
"dataURL": "data:image/jpeg;base64,/9j/4XGiRXh/WU8GGXVL5BHN5PW...",
"width": 3024,
"height": 4032
}
I have a laravel backend with a request validation for this:
rules = [
...
'featured_image' => 'image',
]
However, my laravel backend returns that the featured image field must be an image. So I'm not sure what format the backend expects.
My dropzone component looks like this:
<template>
<div
class="dropzone mb-3 dz-clickable"
:class="[multiple ? 'dropzone-multiple' : 'dropzone-single']"
>
<div class="fallback">
<div class="custom-file">
<input
type="file"
class="custom-file-input"
id="projectCoverUploads"
:multiple="multiple"
/>
<label class="custom-file-label" for="projectCoverUploads"
>Choose file</label
>
</div>
</div>
<div
class="dz-preview dz-preview-single"
v-if="!multiple"
:class="previewClasses"
ref="previewSingle"
>
<div class="dz-preview-cover">
<img class="dz-preview-img" data-dz-thumbnail />
</div>
</div>
<ul
v-else
class="dz-preview dz-preview-multiple list-group list-group-lg list-group-flush"
:class="previewClasses"
ref="previewMultiple"
>
<li class="list-group-item px-0">
<div class="row align-items-center">
<div class="col-auto">
<div class="avatar">
<img class="avatar-img rounded" data-dz-thumbnail />
</div>
</div>
<div class="col ml--3">
<h4 class="mb-1" data-dz-name>...</h4>
<p class="small text-muted mb-0" data-dz-size>...</p>
</div>
<div class="col-auto">
<button data-dz-remove="true" class="btn btn-danger btn-sm">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "dropzone-file-upload",
props: {
options: {
type: Object,
default: () => ({}),
},
value: [String, Object, Array],
url: {
type: String,
default: "http://",
},
multiple: Boolean,
previewClasses: [String, Object, Array],
},
model: {
prop: "value",
event: "change",
},
data() {
return {
currentFile: null,
files: [],
showList: false,
};
},
methods: {
async initDropzone() {
let Dropzone = await import("dropzone");
Dropzone = Dropzone.default || Dropzone;
Dropzone.autoDiscover = false;
let preview = this.multiple
? this.$refs.previewMultiple
: this.$refs.previewSingle;
let self = this;
let finalOptions = {
...this.options,
url: this.url,
thumbnailWidth: null,
thumbnailHeight: null,
previewsContainer: preview,
previewTemplate: preview.innerHTML,
maxFiles: !this.multiple ? 1 : null,
acceptedFiles: !this.multiple ? "image/*" : null,
init: function () {
this.on("addedfile", function (file) {
if (!self.multiple && self.currentFile) {
// this.removeFile(this.currentFile);
}
self.currentFile = file;
});
},
};
this.dropzone = new Dropzone(this.$el, finalOptions);
preview.innerHTML = "";
let evtList = [
"drop",
"dragstart",
"dragend",
"dragenter",
"dragover",
"addedfile",
"removedfile",
"thumbnail",
"error",
"processing",
"uploadprogress",
"sending",
"success",
"complete",
"canceled",
"maxfilesreached",
"maxfilesexceeded",
"processingmultiple",
"sendingmultiple",
"successmultiple",
"completemultiple",
"canceledmultiple",
"totaluploadprogress",
"reset",
"queuecomplete",
];
evtList.forEach((evt) => {
this.dropzone.on(evt, (data) => {
this.$emit(evt, data);
if (evt === "addedfile") {
this.files.push(data);
this.$emit("change", this.files);
} else if (evt === "removedfile") {
let index = this.files.findIndex(
(f) => f.upload.uuid === data.upload.uuid
);
if (index !== -1) {
this.files.splice(index, 1);
}
this.$emit("change", this.files);
}
});
});
},
},
async mounted() {
this.initDropzone();
},
};
</script>
<style></style>
I am new to Knockout JS and think it is great. The documentation is great but I cannot seem to use it to solve my current problem.
The Summary of my Code
I have two viewmodels represented by two js scripts. They are unified in a parent js file. The save button's event is outside
both foreach binders. I can save all data in the details foreach.
My Problem
I need to be able to include the value from the contacts foreach binder with the values from the details foreach binder.
What I have tried
I have tried accessig the data from both viewmodels from the parent viewmodel and sending the POST request to the controller from there but the observeableArrays show undefined.
Create.CSHTML (Using MVC5 no razor)
<div id="container1" data-bind="foreach: contacts">
<input type="text" data-bind="value: contactname" />
</div>
<div data-bind="foreach: details" class="card-body">
<input type="text" data-bind="value: itemValue" />
</div>
The save is outside of both foreach binders
<div class="card-footer">
<button type="button" data-bind="click: $root.save" class="btn
btn-success">Send Notification</button>
</div>
<script src="~/Scripts/ViewScripts/ParentVM.js" type="text/javascript"></script>
<script src="~/Scripts/ViewScripts/ViewModel1.js" type="text/javascript"></script>
<script src="~/Scripts/ViewScripts/ViewModel2.js" type="text/javascript"></script>
ViewModel1
var ViewModel1 = function (contacts) {
var self = this;
self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
return {
contactName: contact.contactName
};
}));
}
ViewModel2
var ViewModel2 = function (details) {
var self = this;
self.details = ko.observableArray(ko.utils.arrayMap(details, function (detail) {
return {
itemNumber: detail.itemValue
};
}));
}
self.save = function () {
$.ajax({
url: baseURI,
type: "POST",
data: ko.toJSON(self.details),
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
window.location.href = "/Home/Create/";
},
error: function (error) {
console.log(error);
window.location.href = "/Homel/Create/";
}
});
};
ParentViewModel
var VM1;
var VM2;
var initialContactInfo = [
{
contactPhone: ""
}
]
var initialForm = [
{
itemValue: ""
]
}
$(document).ready(function () {
if ($.isEmptyObject(VM1)) {
ArnMasterData = new ViewModel1(initialContactInfo);
ko.applyBindings(VM1, document.getElementById("container1"));
}
if ($.isEmptyObject(VM2)) {
VM2 = new ViewModel2(initialForm);
ko.applyBindings(VM2, document.getElementById("container2"));
}
});
I tried unobtrusiveValidation and that is not working for me, it's always breaking on
var unobtrusiveValidation = $form.data('unobtrusiveValidation');
var validator = $form.validate();
And every other solution online for partial view is not working, so what am I doing wrong?
View :
//BUNCH OF HTML
<!-- Modal edit user-->
#Html.Partial("~/Views/User/Partials/ProfileEditUserPartial.cshtml", Model.UserProfileData)
<div id="profileFormContainer" data-url="#Url.Action("ActionName", "ControllerName")"></div>
Partial view:
#model Web.Models.Users.Partials.ProfileEditUserPartialViewModel
<div class="modal fade text-left" id="profileEditUserModalId" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
#using (Html.BeginForm("UpdateUserData", "User", FormMethod.Post,new { id = "profileForm"}))
{
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel1">Edit</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.LabelFor(x => x.UserProfile.FirstName)*
#Html.TextBoxFor(x => x.UserProfile.FirstName, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.UserProfile.FirstName)
#Html.LabelFor(x => x.UserProfile.LastName)*
#Html.TextBoxFor(x => x.UserProfile.LastName, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.UserProfile.LastName)
#Html.LabelFor(x => x.UserProfile.Country)*
#Html.TextBoxFor(x => x.UserProfile.Country, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.UserProfile.Country)
</div>
<div class="modal-footer">
<button type="button" class="btn grey btn-outline-secondary" data-dismiss="modal">#Resources.Resource.General_Close</button>
<button type="button" class="btn btn-outline-success" data-addressId id="saveUserDataId">#Resources.Resource.General_Ok</button>
</div>
}
</div>
</div> </div>
Controller:
public ActionResult UpdateUserData(ProfileEditUserPartialViewModel userModel)
{
var model = PopulateProfileViewModel();
if (!ModelState.IsValid)
{
return PartialView("~/Views/User/Partials/ProfileEditUserPartial.cshtml", userModel);
}
m_UserService.UpdateUserProfile(userModel.UserProfile, GetUser().Id);
m_AccountService.ClearUserCache(GetUser());
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
Controller is like this because I was working with Ajax.beginForm, but let it be like this, that can be changed easily, and most important part is script file
Script:
$('#editUserDataId').click(function () {
$("#profileEditUserModalId").modal("show");
});
$('#saveUserDataId').click(function(){
var $formContainer = $('#profileFormContainer');
var url = $formContainer.attr('data-url');
$formContainer.load(url, function () {
var $form = $('#profileForm')
.removeData("validator")
.removeData("unobtrusiveValidation");
var unobtrusiveValidation = $form.data('unobtrusiveValidation');
var validator = $form.validate();
$.validator.unobtrusive.parse($form);
$form.submit(function () {
var $form = $(this);
if ($form.valid()) {
$.ajax({
url: url,
async: true,
type: 'POST',
data: JSON.stringify("Your Object or parameter"),
beforeSend: function (xhr, opts) {
},
contentType: 'application/json; charset=utf-8',
complete: function () { },
success: function (data) {
$form.html(data);
$form.removeData('validator');
$form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($form);
}
});
}
return false;
});
});
return false;
});
So, I changed partial view:
<div class="modal-dialog" role="document">
<div id="profileInnerDivId" class="modal-content">
#using (Ajax.BeginForm("EditUserAddress", "User", new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "UserAddressUpdated",
InsertionMode = InsertionMode.Replace
}, new { data_accountid= #Model.AddressId }))
{
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel1">Edit</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.HiddenFor(x => x.AddressId)
#Html.LabelFor(x => x.Active)
#Html.RadioButtonFor(x => x.Active, true, new { #class = "opacity-fixed" })
</div>
<div class="modal-footer">
<button type="button" class="btn grey btn-outline-secondary" data-dismiss="modal">#Resources.Resource.General_Close</button>
<button type="submit" class="btn btn-outline-success" data-addressId id="saveEditBtnId">#Resources.Resource.General_Ok</button>
</div>
}
</div>
</div>
And in controller I am using Json:
[HttpPost]
public ActionResult EditUserAddress(UserAddress userAddress)
{
var model = PopulateProfileViewModel();
if (!ModelState.IsValid)
{
return PartialView("~/Views/User/Partials/_ProfileEditUserAddressPartial.cshtml", userAddress);
}
//some code...
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
And finally in my script I have swal that will be triggered and u just need to use HTML function to put code that is returned from action if error is occurred, so error msg will be displayed:
function UserAddressUpdated(result) {
var id = $(this).data('accountid');
if (result.success) {
$("#profileModalId").modal("hide");
swal({
title: Localization.Edit_User_Address_Success_Message,
icon: "success"
}).then(function () {
location.reload();
});
} else {
$("#profileModalId-" + id).html(result);
swal({
title: Localization.Edit_User_Address_Error_Message,
icon: "error"
});
}
}
Concept:
1. Use Ajax.BeginForm, define Success method
2. In Action use Json return type and if error occurred, return that
partial view
3. Use $('divId').html to write your msg.
I trying to build a CRUD using Vue.js and Laravel, but... I can Save, Read and Update the only problem is the Delete, can someone help me?
My index.blade.php: (to get id)
<div class="modal inmodal" id="delete" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content animated bounceInRight">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Fechar</span></button>
<h4 class="modal-title">Delete</h4>
</div>
<div class="modal-body">
<div class="form-group">
<p>Do you want delete this row <strong>ID: </strong> #{{competency.id}} <strong>Nome: </strong> #{{competency.name}} </p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger" v-on:click="remove(competency.id)">Delete</button>
</div>
</div>
</div>
My Vue.js
var competency = new Vue({
el: '#competency',
filters: {
moment: function (date) {
return moment(date).format('DD/MM/YYYY');
}
},
data: {
competency: "",
searchQuery: '',
search: {
name: ""
},
list: [],
},
methods: {
fillCompetency: function(comp){
if (comp == null)
this.competency = {
id : "",
name : "",
description : "",
}
else
this.competency = comp;
},
del: function(index){
this.fillCompetency(this.list[index]);
$("#delete").modal('show');
},
remove: function(id){
var self = this;
self.competency._token = window.Laravel.csrfToken;
$.ajax({
url: "competency",
type: "POST",
dataType: 'json',
traditional: true,
data: id
}).done(function(data){
self.filter();
$("#delete").modal('hide');
fillCompetency(null);
});
}
},
mounted: function () {
this.filter();
},
watch: {
}
});
My Controller
class CompetencyController extends Controller {
public function __construct(){
$this -> middleware('auth');
}
public function index(){
return view('competency/index');
}
public function filter(){
$list = Competency::all();
return response()->json($list);
}
public function create(){
}
public function store(Request $request){
$entity = new Competency;
if ($request->id != null){
$entity = Competency::find($request->id);
}
if ($request->name == null && $request->description == null){
$entity = Competency::find($id);
return response()->json($entity->delete());
}
$entity->name = $request->name;
$entity->description = $request->description;
return response()->json($entity->save());
}
public function delete($id){
$entity = new Competency;
$entity = Competency::find($id);
return response()->json($entity->delete());
}
public function show($id){
}
public function edit($id){
}
public function update(Request $request){
}
public function destroy($id){
$entity = new Competency;
$entity = Competency::find($id);
return response()->json($entity->delete());
}
}
My route:
Route::resource('competency', 'CompetencyController');
The problem is, i have tried to send DELETE method on remove from Vue, but i get an error called 500 (Internal Error Serve) but on laravel.log dont show anything, i have tried send DELETE method because the desroy method is called correct? so i get error instead i send by POST method to store and check if just id is not null, if not i called method delete by laravel, so any method that i hev tried dont work, can someone help me?
I think that the error is on Route, but i tried everything too
Try changing your delete method to this
// your route for delete should be
Route::delete('competency/{id}', 'Controller#delete');
// controller
public function delete($id){
$responseMsg = "Competency not found";
$status = 404;
$entity = Competency::find($id);
if ($entity != null ){
$responseMsg = "Competency deleted";
$status = 204;
$entity->delete(); // delete method is void, doen't return any value
}
return response()->json(['message' => $responseMsg], $status);
}
Vue.js remove method
remove: function(id){
var self = this;
self.competency._token = window.Laravel.csrfToken;
$.ajax({
url: "competency/"+id,
type: "DELETE", //
traditional: true
// if you use POST method, data has to be a json object
// {id: id} then in laravel you could do $request->input('id');
}).done(function(data){
self.filter();
$("#delete").modal('hide');
fillCompetency(null);
});
}
I am new to Knockout.js, i have 2 viewModel EmployeeviewModel and DepartmentViewModel, i am binding my first view using EmployeeviewModel its working perfect, now i need make click so i can navigate to second page which is department and in frist i need to display click EmployeeName and his department, secondly i need to display all the EmployeeName related to that department how to achive this, how i can pass my first page value to second page display related to departmentID.
function EmployeeViewModel()
{
var self =this;
var Allemployee =ko.observableArray([])
self.getEmployeedetails=function ()
$.ajax({
type: "GET",
dataType: "json",
url: baseUrl + 'xxx/xxxxxx',
success: function (data) {
self.Allemployee($.map(data, function (item) {
return new EmployeeModel(item);
}));
},
error: function (error) {
}
});
self.getDepartment=function()
{
//here i need to navigate to Department page with all department ID
}
}
function EmployeeModel(data)
{
var self =this;
self.employeeName = ko.observable(data.employeeName )
self.employeeMobile= ko.observable(data.employeeMobile)
self.employeeemail = ko.observable(data.employeeemail )
self.employeedepartmentId= ko.observable(data.employeedepartmentId)
}
function DepartmentViewModel()
{
var self =this;
var AllDepartmentemployee =ko.observableArray([])
self.getEmployeedetails=function ()
$.ajax({
type: "GET",
dataType: "json",
url: baseUrl + 'xxx/xxxxxx',
success: function (data) {
self.AllDepartmentemployee ($.map(data, function (item) {
return new DepartmentModel(item);
}));
},
error: function (error) {
}
});
}
function DepartmentModel (item)
{
self.departmentId= ko.observable(data.departmentId)
self.departmentName=ko.observable(data.departmentName)
self.employeeName=ko.observable(data.employeeName)
}
var viewModel=new EmployeeViewModel()
ko.applyBindings(EmployeeViewModel,document.getElementById("employeeDetails"))
var viewModel 2=new DepartmentViewModel()
ko.applyBindings(viewModel,document.getElementById("department"))
//html//
//First view
<div data-role="view" id="employeeDetails">
<ul>
<li>
<div data-bind="text:employeeName"></div>
<div data-bind="text:employeeMobile"></div>
<div data-bind="text:employeeemail "></div>
<div data-bind="text:employeedepartmentId"></div>
</li>
</ul>
<div>
//second View
<div data-role="view" id="department">
<div data-bind="text:employeeName">
<div>
<div data-bind="text:departmentName">
<div>
<ul data-bind:"foreach:AllDepartmentemployee">
<li>
<div data-bind="text:employeeName">
<div data-bind="text:departmentName"></div>
</li>
<ul>
<div>
You need to have a Main view model and have two sub view models for your departments and employees. Then every time you click on any employee you will have the departmentId then based on your logic you can either send a request to the server along with Id and get back all the employees under that department or you already have all departments and you just filter them based on departmentId that has been passed.
Below is an example how to handle: https://jsfiddle.net/kyr6w2x3/124/
HTML:
<div data-role="view" id="employeeDetails">
<ul >
<li>
<span class="info">Name</span>
<span class="info">Mobile</span>
<span class="info">Email</span>
<span class="info">Dept.NO</span>
</li>
<hr>
<!-- ko foreach: AllEmployee -->
<li>
<span data-bind="text:EmployeeName" class="info"></span>
<span data-bind="text:EmployeeMobile" class="info"></span>
<span data-bind="text:EmployeeEmail " class="info"></span>
<span data-bind="text:EmployeeDepartmentId" class="info"></span>
Click
</li>
<!-- /ko -->
</ul>
<div>
//second View
<div data-role="view" id="department">
<h1 data-bind="text:SelectedEmployeeName"></h1>
<div data-bind="if:AllDepartmentEmployee().length > 0">
<h3 data-bind ="text:AllDepartmentEmployee()[0].DepartmentName()"></h3>
</div>
<ul data-bind ="foreach:AllDepartmentEmployee">
<li>
<div data-bind="text:EmployeeName"></div>
<!-- <div data-bind="text:DepartmentName"></div> -->
</li>
<ul>
<div>
VM:
var employeesList = [{
employeeId : 1,
employeeName:"Mike" ,
employeeMobile :1234561 ,
employeeEmail:"Mike#example.com",
employeeDepartmentId:1},
{
employeeId : 2,
employeeName:"Alex" ,
employeeMobile :1234562 ,
employeeEmail:"Alex#example.com",
employeeDepartmentId:1
},
{
employeeId : 3,
employeeName:"Dave" ,
employeeMobile :1234563 ,
employeeEmail:"Dave#example.com",
employeeDepartmentId:1
},
{
employeeId : 4,
employeeName:"Dani" ,
employeeMobile :1234564 ,
employeeEmail:"Dani#example.com",
employeeDepartmentId:2},
{
employeeId : 5,
employeeName:"Chris" ,
employeeMobile :1234565 ,
employeeEmail:"Chris#example.com",
employeeDepartmentId:2
},
{
employeeId : 6,
employeeName:"Matt" ,
employeeMobile :1234566 ,
employeeEmail:"Matt#example.com",
employeeDepartmentId:2
}
]
var departmentsList = [
{departmentId:1,
departmentName:"Dept #1",
employeeName:"Mike"
},
{departmentId:1,
departmentName:"Dept #1",
employeeName:"Alex"
},
{departmentId:1,
departmentName:"Dept #1",
employeeName:"Dave"}
,
{departmentId:2,
departmentName:"Dept #2",
employeeName:"Matt "
},
{departmentId:2,
departmentName:"Dept #2",
employeeName:"Dani"
},
{departmentId:2,
departmentName:"Dept #2",
employeeName:"Chris "}
]
function MainViewModel(){
var self = this;
self.AllEmployee = ko.observableArray([]);
self.AllDepartmentEmployee= ko.observableArray([]);
self.SelectedEmployeeName = ko.observable();
self.LoadEmployees = function (){
// Ajax goes here to load uncomment below
// $.ajax({
// type: "GET",
// dataType: "json",
// url: baseUrl + 'xxx/xxxxxx',
// success: function (data) {
self.AllEmployee($.map(employeesList, function (item) {
return new EmployeeModel(item);
}));
// },
// error: function (error) {
// }
//});
}
self.GetDepartment = function(employee){
self.SelectedEmployeeName(employee.EmployeeName())
data = {departmentId:employee.EmployeeDepartmentId()}
// $.ajax({
// type: "GET",
// data:data,
// dataType: "json",
// url: baseUrl + 'xxx/xxxxxx',
// success: function (data) {
// HERE YOU MAY JUST GET THE LIST OF EMPLOEES FOR THIS DEPARTMENT OR YOU GET ALL AND HERE YOU FILTER
self.AllDepartmentEmployee ($.map(departmentsList, function (item) {
if(item.departmentId == employee.EmployeeDepartmentId()){
return new DepartmentModel(item);
}
}));
// },
// error: function (error) {
// }
// });
}
}
function EmployeeModel(data){
var self = this;
self.EmployeeId = ko.observable(data.employeeId);
self.EmployeeName = ko.observable(data.employeeName);
self.EmployeeMobile= ko.observable(data.employeeMobile);
self.EmployeeEmail = ko.observable(data.employeeEmail );
self.EmployeeDepartmentId= ko.observable(data.employeeDepartmentId);
}
function DepartmentModel (data){
var self = this;
self.DepartmentId = ko.observable(data.departmentId)
self.DepartmentName = ko.observable(data.departmentName)
self.EmployeeName = ko.observable(data.employeeName)
}
var viewModel = new MainViewModel();
ko.applyBindings(viewModel);
viewModel.LoadEmployees();