Foreach Data not reflected to UI with Knouckout Js Object Obserable - javascript

Below is the view modal where I am getting the ajax response and load to the obserable value.
var userManagementVM = {
responseSetUpData: ko.observable({
userList: ko.observable(),
userListViewModel: ko.observableArray(),
MeetingId: ko.observable(),
MeetingTypeId: ko.observable(),
MeetingType: ko.observable()
}),
SetListOfUserInRoles: function () {
var self = this;
var ajaxUrl = ApplicationRootUrl("UserRoleManagement", "UserManagement");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: ajaxUrl,
dataType: "json",
success: function (data) {
self.responseSetUpData(data);
console.log(self.responseSetUpData())
},
error: function (err) {
}
});
}
}
$(document).ready(function () {
ko.applyBindings(userManagementVM, document.getElementById("rightdash-container"));
userManagementVM.SetListOfUserInRoles();
});
The response from the ajax is successfully loaded to the obserable value. Below is the output of the console
HTML code
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Users</th>
<th scope="col">Role</th>
</tr>
</thead>
<tbody data-bind="foreach: responseSetUpData.userListViewModel">
<tr>
<td><input class="form-check-input" type="checkbox" data-bind="checked: SelectedUser"><span data-bind="text: $data.FirstName"></span></td>
<td><select data-bind="options: $data.Roles,optionsText: 'Name',value: $data.SelectedRoleId,optionsCaption: '-- Select Role --'"></select></td>
</tr>
</tbody>
</table>
The value is not bind to the UI.

You need to get the value of the observable - responseSetUpData() in the binding:
<tbody data-bind="foreach: responseSetUpData().userListViewModel">
Otherwise you are trying to get userListViewModel from the observable function object :-)

Related

Array List is not binding to thymeleaf table

I'm using thyme leaf. I have a table that displays dynamic records. I have tried 2 approaches to display the records, but the values are not binding.
Approach - 1
Using JQuery
$().ready(function () {
getTableDetails();
});
function getTableDetails() {
try {
var ajaxCall;
ajaxCall = $.ajax({
url: /getTableDetails
type: 'GET',
async:false,
dataType: 'json'
});
ajaxCall.done(function (data, textStatus, jqXHR) {
alert(JSON.stringify(data));
$.each(data, function (i, p) {
$('#details').append($('<tbody></tbody>').val(p).html(p));
});
});
ajaxCall.fail(function (jqXHR, textStatus, errorThrown) {
// handle failure cases
alert(textStatus+errorThrown);
});
} catch (e) {
}
}
HTML File
<table class="indi-data-table__table">
<thead>
<tr>
<th scope="col" class="datatable-column-width125" role="columnheader">
<div class="indi-data-table__column-heading">ID</div>
</th>
<th scope="col" class="datatable-column-width150" role="columnheader">
<div class="indi-data-table__column-heading">NAME</div>
</th>
</tr>
</thead>
<tbody id="details">
<tr th:each="row : ${tableDetailList}">
<td th:text="${row.id}"/>
<td th:text="${row.name}"/>
</tr>
</tbody>
</table>
Approach - 2
Using Model getAttribute from Java
#RequestMapping(value = "/getTableDetails", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<DataEntity> getTableDetails(Model model) throws JsonProcessingException {
List<DataEntity> tableDetailList = new ArrayList<>();
try {
tableDetailList.addAll(repoCall);
} catch (Exception ex) {
ex.getCause().printStackTrace();
}
model.addAttribute("tableDetailList", tableDetailList);
return tableDetailList;
}
I have also tried
<tr th:each="row : ${tableDetailList}">
<td th:text="${row.getId()}"/>
<td th:text="${row.getName()}"/>
</tr>
But, none of them is actually binding the values, I am getting the response from the API.
Any help is much appreciated.
Thank you!

How can I give Ajax data (list) to mustache?

I want to put the user object I received as Ajax into {{#user}} in mustache and render it on the screen.
<table class="table table-horizontal table-bordered">
<thead class="thead-strong">
<tr>
<th>user number</th>
</tr>
</thead>
<tbody id="tbody">
{{#users}}
<tr>
<td>{{id}}</td>
</tr>
{{/users}}
</tbody>
</table>
this is conroller
#PostMapping("/api/v1/eduPosts/registerAdminToUser")
public List<User> registerAdminToUser(#RequestBody UserRegisterRequestDto userRegisterRequestDto){
List<User> users=userService.registerAdminToUser(userRegisterRequestDto);
System.out.println(users);
return users;
}
this is index.js
update : function () {
var data = {
adminId: $('#adminId').val(),
userId: $('#userId').val()
};
//var id = $('#id').val();
$.ajax({
type: 'POST',
url: '/api/v1/eduPosts/registerAdminToUser',
dataType: 'json',
contentType:'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function(data) {
$.each(data, function(idx, val) {
alert(idx + " " + val.id);
console.log(idx + " " + val.id)
});
alert(JSON.stringify(data))
}).fail(function (error) {
alert(JSON.stringify(error));
});
}
Should I change the js file? Or do I have to change the mustache template?
If I print out the user object in the index.js file, the data is being rendered properly.
Thanks!

Ng-table not calling get data

I've got implemented ng-table with an ajax call but never call the function from getdata, the function onBuscarTable is never call, I've look at the debbugger console to check it and dosen't call it:
what i'm doing whrong?
here's the js:
$scope.onBuscarTable = function ($defer, params) {
$.ajax({
type: 'GET',
url: '/Home/GetEfficiencyDetails',
cache: false,
contentType: 'application/json; charset=utf-8',
//data: JSON.stringify({ title: "fghfdhgfdgfd" }),
success: function (data) {
$scope.items = data;
$defer.resolve(data);
}
});
};
//$scope.getEffiencyDetails();
$scope.tableBuscar = new ngTableParams({
page: 1, // show first page
count: $scope.items.length, // hides pager
sorting: {
name: 'asc' // initial sorting
}
}, {
counts: [], // hides page sizes
getData: $scope.onBuscarTable
});
$scope.tableBuscar.reload();
and here is the html:
<table ng-table="tableBuscar" show-filter="true" class="table table-striped table-bordered table-condensed table-hover">
<tbody>
<tr>
<th colspan="5">Battery Life</th>
<th colspan="4">SBC</th>
<th colspan="3">ZBC</th>
<th>Overall</th>
</tr>
<tr>
<th>Pool #</th>
<th>True Cap.</th>
<th>Util.</th>
<th>Load Sharing</th>
</tr>
<tr ng-repeat="item in items">
<td>{{item.PoolName}}</td>
<td>{{item.AvgTrueCapacity}}</td>
<td>{{item.AvgEnergyUsageDaily}}</td>
</tr>
</tbody>
</table>
You code should using $http instead of $.ajax
$scope.items = [];
$scope.onBuscarTable = function($defer, params) {
$http.get('/Home/GetEfficiencyDetails').success(function(data) {
$scope.items = data;
$defer.resolve(data);
});
};
//$scope.getEffiencyDetails();
$scope.tableBuscar = new ngTableParams({
page: 1, // show first page
count: $scope.items.length, // hides pager
sorting: {
name: 'asc' // initial sorting
}
}, {
counts: [], // hides page sizes
getData: $scope.onBuscarTable
});
$scope.tableBuscar.reload();

model not passing to controller from view

I am new to mvc and javascript.At first I am using javascript to appned the parital view in divsion
$('.btngo').click(function (e) {
var fid = $('#FiscalYear_FYId').val();
alert($('#FiscalYear_FYId').val());
$.ajax({
type: 'Get',
url: '#Url.Action("RateList", "Rate")',
data: { fyid: fid },
success: function (sc) {
$('#Ratelist').html(sc);
}
});
});
The partial view is of model FHIControl.Model.StationeryRate.RateDTO which consists a submit button my view looks like
#using (Html.BeginForm("Ratelist", "Rate", FormMethod.Post))
{
#Html.ValidationSummary(true)
<table>
<thead>
<tr>
<th>Item Id</th>
<th>Item Name</th>
<th>Rate</th>
</tr>
</thead>
#Html.HiddenFor(x=>Model.FiscalYear.FYId)
#foreach (var item in Model.RateList)
{
<tr>
#Html.HiddenFor(x => item.ItemId)
<td>#{count++;}#count</td>
<td>#Html.DisplayFor(x => item.ItemName)</td>
<td>#Html.TextBoxFor(x => item.Rate)</td>
</tr>
}
</table>
<p>
<input type="submit" value="Ok" id="btnsubmit" />
</p>
}
The button submit is submiting the form but there is no model items.Why is it so?Is there any way to make this work?
There is no model items because you are only passing the value of FiscalYear_FYId:
var fid = $('#FiscalYear_FYId').val();
$.ajax({
data: { fyid: fid },
});
which should be:
$.ajax({
data: $form.serialize(),
});
where $form is a reference to your form. That you can either give a name for faster and better reference, or you can reference it like this:
var $form = $("#btnsubmit").parents('form');

ASP.NET using Knockout.js and mappings

Using the following code i experience a strange problem. When I click and call showVacationModal data is retrieved fine from the server and result is displayed correctly. If i keep clicking the same person(id) it continues to work.
If I click a different person (eg. different id) with no vacations nothing is showed = OK.
The problem
Now when I click the first person again nothing is displayed. (data is retrieved fine in ajax call).
Any ideas?
My JS code:
var ViewModel = function () {
this.vacations = ko.mapping.fromJS(null);
};
var model = new ViewModel();
function showVacationModal(id) {
var model = {};
$.ajax({
type: "POST",
url: "Default.aspx/GetVacations",
data: "{personId: '" + id + "'}",
delay: 1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
model.vacations = ko.mapping.fromJS(msg.d);
ko.applyBindings(model);
$('#vacationModal').modal('show')
}
});
}
My HTML:
<table>
<thead>
<tr>
<th>
First name
</th>
<th>
Last name
</th>
</tr>
</thead>
<tbody data-bind="foreach: vacations">
<tr>
<td data-bind="text: Id">
</td>
<td data-bind="text: PersonId">
</td>
<td data-bind="text: Begin">
</td>
</tr>
</tbody>
</table>
Have you tried something more like this?
function showVacationModal(id) {
// var model = {}; no need to reset the model property
$.ajax({
type: "POST",
url: "Default.aspx/GetVacations",
data: { personId: id }, // why wrap data in strings?
delay: 1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//model.vacations = ko.mapping.fromJS(msg.d);
ko.mapping.fromJS(msg.d, {}, model.vacations);
// ko.applyBindings(model); no need to reapply bindings
$('#vacationModal').modal('show')
}
});
}
See this ko.mapping documentation section for more information.

Categories