How to get values from a loop defined in Knockout JS UI - javascript

I have two arrays : Schedules and ControllerDoors and the values come from a Controller.
The ViewModel looks like :
getAddDetails: function (siteId) {
var SiteId = siteId;
this.postDataRequest('/GetAddDetails', { Id: SiteId }, function (err, result) {
if (!err && result && result.success) {
debugger;
var scheduleData = result.data1;
var controllerDoorData = result.data2;
this.AddModel.Schedules(scheduleData);
this.AddModel.ControllerDoors(_.map(controllerDoorData || [], function (item) {
return new ISP.AddPanelModel(item);
}));
And in Controller
[HttpPost]
[NoCache]
public async Task<JsonResult> GetAddDetails (string Id)
{
try
{
var scheduleList = new[]
{
new { ScheduleId = "Schedule1",ScheduleName = "Always On" },
new { ScheduleId = "Schedule2",ScheduleName = "Never On"}
};
var doorsForSite = new[]
{
new { ControllerId ="controller1",ControllerName="Eagle",IsChecked = "false",
Doors = new[]
{
new { DoorId="Door1",DoorName="DoorOne"},
new { DoorId = "Door2", DoorName = "DoorTwo" }
}
},
new { ControllerId ="controller2",ControllerName="NetAxis",IsChecked = "false",
Doors = new[]
{
new { DoorId= "Door3",DoorName="DoorThree"},
new { DoorId = "Door4", DoorName = "DoorFour" },
new { DoorId = "Door5", DoorName = "DoorFive" }
}
}
};
return Json(new { success = true, data1 = scheduleList, data2 = doorsForSite }, JsonRequestBehavior.AllowGet);
}
catch(Exception e)
{
return Json(new { success = false, errorMessage = System.Web.Helpers.Resources.General_error });
}
}
So effectively , each ControllerDoor array item will have Doors array inside and Schedules is a separate array.
But in UI , I need to populate the schedule dropdown for each door and on press of Save , I need each one of the Schedule Values corresponding to each door.
UI
<ul class="accgrouptableaccordian scroll-x scroll-y">
<!-- ko foreach: $data.AddModel.ControllerDoors -->
<li>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<span>
<span>
<span class="ispicon ispicon_accordian_droparrow">
</span>
<span class="title" style="line-height:20px;" data-bind="text: ControllerName() + ' - ' + Doors().length + ' Doors'">
</span>
</span>
<span>
</span>
</span>
</h4>
</div>
<div class="panel-collapse">
<div class="panel-body">
<div class="table-responsive panel-body">
<table class="table">
<tbody data-bind="foreach:Doors">
<tr>
<td>
<div>
<span data-bind="text:DoorId"></span>
</div>
</td>
<td class="col-md-4">
<select name="drpSchedulesAccess" class="form-control drpSchedulesAccess" data-bind="options:$root.AddModel.Schedules,
optionsText: 'ScheduleName',
optionsValue: 'ScheduleId',
value: $data.ScheduleId"></select>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</li>
<!-- /ko -->
</ul>
But this is the problem.
Schedule is a separate array and in UI it seems each door can have it's own schedule.
But if I do this.AddModel.Schedules , I only get the two values.
I need to get the five Schedule values corresponding to five doors displayed.
How to do it ? Please help.

Related

Vue method not passing data to array of objects

So I'm going to be explaining this in the best way possible as I don't understand what might be causing this issue on my end as I feel like I've followed all of the directions and keep hitting a brick wall.
Here is my vue.js app:
new Vue({
name: 'o365-edit-modal-wrapper',
el: '#o365-modal-edit-wrapper',
data: function() {
const default_apps = [
{
'post_title': 'Excel',
}, {
'post_title': 'Word',
}, {
'post_title': 'SharePoint',
}];
console.log(default_apps);
const default_apps1 = this.get_array_of_post_objects('application_launcher');
console.log(default_apps1);
return {
available_list: [],
selected_list: default_apps.map(function(name, index) {
return {
name: name.post_title,
order: index + 1,
fixed: false
};
}),
}
},
methods: {
get_array_of_post_objects(slug) {
let items = [];
wp.api.loadPromise.done(function () {
const Posts = wp.api.models.Post.extend({
url: wpApiSettings.root + 'menus/v1/locations/' + slug,
});
const all_posts = new Posts();
all_posts.fetch().then((posts) => {
items.push(...posts.items);
});
});
return items;
},
},
computed: {
dragOptions() {
// Pass in additional <draggable> options inside the return for both lists.
return {
tag: 'div',
group: 'o365apps',
disabled: !this.editable,
ghostClass: "ghost",
};
},
},
});
Inside my methods, I have a method called get_array_of_post_objects which returns an array of objects that I'm pulling through.
So inside data, I'm console logging my manual default_apps and my default_apps1 which is the method. Both of the arrays of objects have post_title: "something" inside.
Here is the return that I'm getting:
Inside my mapping, when I define default_apps, my IDE returns some result for name but when I switch it over to default_apps1, it's not finding any results as shown below:
I don't know what else to look at - All help would be appreciated!
Here is the HTML code if that is needed:
<div class="column is-half-desktop is-full-mobile buttons">
<nav class="level is-mobile mb-0">
<div class="level-left">
<div class="level-item is-size-5 has-text-left">Selected</div>
</div>
<div class="level-right">
<div class="level-item" #click="orderList()"><i class="fas fa-sort-alpha-up is-clickable"></i></div>
</div>
</nav>
<hr class="mt-1 mb-3">
<!-- Decorator: # also known as v-on: -->
<!-- Bind: : also known as v-bind: -->
<draggable class="list-group"
v-model="selected_list"
v-bind="dragOptions"
:move="onMove"
#add="onAdd"
#remove="onRemove"
#start="isDragging=true"
#end="isDragging=false">
<button class="button is-fullwidth is-flex list-group-item o365_app_handle level is-mobile" v-for="(app, index) in selected_list" :key="app.order">
<div class="level-left">
<span class="icon" aria-hidden="true">
<img :src="`<?= Path::o365('${app.name}' . '.svg'); ?>'`" />
</span>
<span>{{app.name}}</span>
</div>
<div class="level-right is-hidden-desktop">
<span class="icon has-text-danger is-clickable" #click="remove(index)">
<i class="fas fa-times"></i>
</span>
</div>
</button>
</draggable>
</div>
I'm not 100% sure what your app is supposed to do, so modify it for your needs.
Here the selected_list will be empty first.
Then we call your method, which is asynchronous, and once it's done selected_list gets populated.
new Vue({
name: 'o365-edit-modal-wrapper',
el: '#o365-modal-edit-wrapper',
data: function() {
return {
available_list: [],
selected_list: [],
}
},
created() {
this.get_array_of_post_objects("add-your-slug")
},
methods: {
get_array_of_post_objects(slug) {
wp.api.loadPromise.done(function() {
const Posts = wp.api.models.Post.extend({
url: wpApiSettings.root + 'menus/v1/locations/' + slug,
});
const all_posts = new Posts();
all_posts.fetch().then((posts) => {
// You might want to modify posts for your needs
this.selectedList = posts
});
});
},
},
});

MVC Razor view need to update controls with Javascript

I have an MVC website using Razor views. My Model is a List<Device>. In this particular view I need to enter a serial number for the device's box and, if it matches the device's serial number, change the dropdown enum from LabelPack to SystemPack. Finally, the controller will update the device's status in the DB.
Here is the relevant code from the view:
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.SerialNumber)
</td>
<td>
<input type="text" id=#item.SerialNumber name=#item.SerialNumber oninput="return boxSerialNumberInput(#item.SerialNumber)" />
</td>
<td>
<div class="col-md-10" id="#item.SerialNumber">
#Html.EnumDropDownListFor(modelItem => item.Status, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(modelItem => item.Status, "", new { #class = "text-danger" })
</div>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID })
</td>
</tr>
}
My question is basically: How do I check if the input serial number matches the device's serial number and update the dropdown? I assume there is a way to do this with JavaScript so I am calling a JavaScript method with the onInput event. However, I don't know what to put in the JavaScript method.
Fortunately, a coworker was able to help me with this. I'm sorry I didn't give enough information in the initial question. I really thought there would be an easy way to do this but it seems there is now. Below is the complete code from my view in case someone else stumbles into the same problem.
#model IEnumerable<DHLScanner.Models.Device>
#{
ViewBag.Title = "LabelPackStationView";
}
#using (Html.BeginForm("LabelPackStation", "Device", FormMethod.Post, new { id = "frmPackStation" }))
{
<p>
Find by serial number: #Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
<div>
<h4>Device</h4>
<hr />
<dl class="dl-horizontal"></dl>
</div>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.SerialNumber)
</th>
<th>
#Html.DisplayName("Box Serial Number")
</th>
<th>
#Html.DisplayNameFor(model => model.Status)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<span id="sp_#item.ID">#Html.DisplayFor(modelItem => item.SerialNumber)</span>
</td>
<td>
<input type="hidden" id="hdn_#item.ID" value="#item.ID" />
<input type="text" id="ser_#item.ID" oninput="return boxSerialNumberInput(#item.SerialNumber)" />
</td>
<td>
<div class="col-md-10">
#Html.EnumDropDownListFor(modelItem => item.Status, htmlAttributes: new { #class = "form-control", id = "ddl_" + #item.ID, name = "ID" })
#Html.ValidationMessageFor(modelItem => item.Status, "", new { #class = "text-danger" })
</div>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID })
</td>
</tr>
}
</table>
<p id="test"> xyz</p>
<p id="links">
#Html.ActionLink("Back to Prep", "PrepStation", "Order", new { id = ViewBag.Order.ID }, null)
#{
if (ViewBag.ShowSystemPackView)
{
#Html.ActionLink("Advance to System Pack", "SystemPackStation", "Order", new { id = ViewBag.Order.ID }, null)
}
}
</p>
<input type="hidden" name="testField" value="a value here" id="testField" />
<input type="hidden" id="hdn_Url" value="#ViewBag.Url" />
<input type="hidden" id="hdn_OrderId" name="ID" value="#ViewBag.Order.ID" />
<button id="btn_Refresh" name="pageRefrersh" value="refresh">Refresh</button>
}
#*<form action="" method="post"></form>*#
<script type="text/javascript">
function RegisterEvents(){
$('input[id^="ser"]').blur(function () {
var Id = $(this).siblings('input[type="hidden"]').val();
var lbl = $('span[id="sp_' + Id + '"]');
if ($(this).val() == lbl.html()) {
$('select#ddl_' + Id).val('3');
}
});
$('button[id="btn_Refresh"]').click(function () {
CollectDeviceData();
return false;
});
}
function CollectDeviceData() {
var devices = new Array();
// Collect Data
$.each($('input[id^="ser"]'), function () {
var Id = $(this).siblings('input[type="hidden"]').val();
var orderId = $('input[id="hdn_OrderId"]').val();
var device = {};
device.Id = Id;
device.Status = $('select#ddl_' + Id).val();
device.OrderID = orderId;
devices.push(device);
});
var jsonObject = {
devices: JSON.stringify(devices)
};
//Return Data
var results = function (data) {
window.location.href = $('input[id="hdn_Url"]').val();
};
PostBack(jsonObject, results);
}
function PostBack(jsonObject, result) {
var url = $('input[id="hdn_Url"]').val();
$.ajax({
url: url,
type: 'post',
data: jsonObject,
success: result,
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}
$(document).ready(function () {
RegisterEvents();
});
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

knockout.js remove doesn't work with nested viewmodel and viewmodel in main viewmodel

<div data-bind="with: SimpleListModel">
<form data-bind="submit: addItem" >
New item:
<input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
<p>Your items:</p>
<select multiple="multiple" width="50" data-bind="options: items"> </select>
</form>
</div>
<div data-bind="with: SimpleListModel2">
<div data-bind="foreach: baselist">
<div>
<span data-bind="text: basename"></span>
<div data-bind="foreach: subItems">
<span data-bind="text: subitemname"></span>
Del
</div>
</div>
<button data-bind="click:$parent.addChild">Add</button>
</div>
</div>
this is the viewmodel
var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable
}
}.bind(this); // Ensure that "this" is always this view model
};
var initialData = [
{ basename: "Danny", subItems: [
{ subitemname: "Mobile"},
{ subitemname: "Home"}]
},
{ basename: "Sensei", subItems: [
{ subitemname: "Mobile"},
{ subitemname: "Home"}]
}];
var SimpleListModel2 = function(baselist) {
var self= this;
self.baselist= ko.observableArray(baselist);
self.addChild = function(list) {
alert(list.basename);
}.bind(this);
self.removecard = function (data) {
//tried
data.baselist.subItems.remove(data);
data.subItems.remove(data);
$.each(self.baselist(), function() { this.subItems.remove(data) })
};
};
var masterVM = (function () {
var self = this;
self.SimpleListModel= new SimpleListModel(["Alpha", "Beta", "Gamma"]);
self.SimpleListModel2= new SimpleListModel2(initialData);
})();
ko.applyBindings(masterVM);
This is a small code snippet i constructed of my project. Can someone make remove card work? last two increments of my questions are of the same type. but this question is the highest i reach.
removecard doesn't work now in this scenario at least for me.
Use $parents[index] to get to specific parent. http://knockoutjs.com/documentation/binding-context.html.
$parents[0] --> parent
$parents[1] --> grand parent
etc
var initialData = [
{ basename: "Danny", subItems: [
{ subitemname: "Mobile"},
{ subitemname: "Home"}]
},
{ basename: "Sensei", subItems: [
{ subitemname: "Mobile"},
{ subitemname: "Home"}]
}];
var SimpleListModel2 = function(baselist) {
var self= this;
self.baselist= ko.observableArray(baselist);
self.addChild = function(list) {
alert(list.basename);
}.bind(this);
self.removecard = function (data) {
//tried
console.log(data);
};
};
var masterVM = (function () {
var self = this;
self.SimpleListModel2= new SimpleListModel2(initialData);
})();
ko.applyBindings(masterVM);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="with: SimpleListModel2">
<div data-bind="foreach: baselist">
<div>
<span data-bind="text: basename"></span>
<div data-bind="foreach: subItems">
<span data-bind="text: subitemname"></span>
Del
</div>
</div>
<button data-bind="click:$parent.addChild">Add</button>
</div>
</div>

How to calculate grand total from a list

I'm making an POS application on mobile phone and I have a question. How do I calculate the grand total from the list of item from the database?
Here's my code
order-detail.dxview
POSApp.OrderDetail = function (params, viewInfo) {
"use strict";
var id = params.id,
order = new POSApp.OrderViewModel(),
isReady = $.Deferred(),
// Item List
shouldReload = false,
dataSourceObservable = ko.observable(),
dataSource;
function handleViewShown() {
POSApp.db.Orders.byKey(id).done(function (data) {
order.fromJS(data);
isReady.resolve();
});
// Item List
if (!dataSourceObservable()) {
dataSourceObservable(dataSource);
dataSource.load().always(function () {
isReady.resolve();
});
}
else if (shouldReload) {
refreshList();
}
// Item List
}
// Item List
function handleViewDisposing() {
POSApp.db.OrderDetails.off("modified", handleOrderDetailsModification);
}
function handleOrderDetailsModification() {
shouldReload = true;
}
// Item List
dataSource = new DevExpress.data.DataSource({
store: POSApp.db.OrderDetails,
map: function (item) {
return new POSApp.OrderDetailViewModel(item);
},
expand: ["Item"],
sort: { field: "OrderDetailId", desc: false },
filter: ["OrderId", parseInt(id)]
});
POSApp.db.OrderDetails.on("modified", handleOrderDetailsModification);
var viewModel = {
grandTotal: ko.observable(total),
handleDelete: function () {
DevExpress.ui.dialog.confirm("Are you sure you want to delete this item?", "Delete item").then(function (result) {
if (result)
handleConfirmDelete();
});
},
handleConfirmDelete: function () {
POSApp.db.Orders.remove(id).done(function () {
if (viewInfo.canBack) {
POSApp.app.navigate("Orders", { target: "back" });
}
else {
POSApp.app.navigate("Blank", { target: "current" });
}
});
},
//Item List
refreshList: function () {
shouldReload = false;
dataSource.pageIndex(0);
dataSource.load();
},
//Item List
// Return
id: id,
order: order,
viewShown: handleViewShown,
isReady: isReady.promise(),
// Item List
dataSource: dataSourceObservable,
viewDisposing: handleViewDisposing,
// Item List
// Return
};
return viewModel;
};
order-detail.js
<div data-options="dxView : { name: 'OrderDetail', title: 'Order' } " >
<div data-bind="dxCommand: { onExecute: '#OrderEdit/{id}', direction: 'none', id: 'edit', title: 'Edit', icon: 'edit' }"></div>
<div data-bind="dxCommand: { onExecute: handleDelete, id: 'delete', title: 'Delete', icon: 'remove' }"></div>
<div data-options="dxContent : { targetPlaceholder: 'content' } " class="dx-detail-view dx-content-background" data-bind="dxDeferRendering: { showLoadIndicator: true, staggerItemSelector: 'dx-fieldset-header,.dx-field', animation: 'detail-item-rendered', renderWhen: isReady }" >
<div data-bind="dxScrollView: { }">
<div class="dx-fieldset">
<div class="dx-fieldset-header" data-bind="text: order.PhoneNumber"></div>
<div class="dx-field">
<div class="dx-field-label">Order id</div>
<div class="dx-field-value-static" data-bind="text: order.OrderId"></div>
</div>
<div class="dx-field">
<div class="dx-field-label">Phone number</div>
<div class="dx-field-value-static" data-bind="text: order.PhoneNumber"></div>
</div>
<div class="dx-field">
<div class="button-info" data-bind="dxButton: { text: 'Add Item', onClick: '#AddItem/{id}', icon: 'add', type: 'success' }"></div>
<!-- Item List -->
<div data-bind="dxList: { dataSource: dataSource, pullRefreshEnabled: true }">
<div data-bind="dxAction: '#OrderDetailDetails/{OrderDetailId}'" data-options="dxTemplate : { name: 'item' } ">
<!--<div class="list-item" data-bind="text: Item().ItemName"></div>
<div class="list-item" style="float:right;" data-bind="text: Amount"></div>-->
<div class="item-name" data-bind="text: Item().ItemName"></div>
<div class="item-amount" data-bind="text: Amount"></div>
<div class="clear-both"></div>
</div>
</div>
</div>
<div class="dx-field">
<div class="dx-field-label">Grand total</div>
<!--<div class="dx-field-value-static" data-bind="text: order.GrandTotal"></div>-->
<div class="dx-field-value-static" data-bind="text: grandTotal"></div>
</div>
</div>
<div data-options="dxContentPlaceholder : { name: 'view-footer', animation: 'none' } " ></div>
</div>
</div>
</div>
I've tried by using get element by class name and it still doesn't work.
I've tried by using get element by class name and it still doesn't work.
You shouldn't try to get the data from your view; it's already in your viewmodel!
This documentation page tells me you can get an array of items from your DataSource instance by calling the items method.
From your data source's map function and your text: Amount data-bind, I figured each item probably has an Amount property which holds an integer.
grandTotal can be a computed that adds these values together whenever dataSourceObservable changes:
grandTotal: ko.computed(function() {
var total = 0;
var currentDS = dataSourceObservable();
if (currentDS) {
var currentItems = currentDS.items();
total = currentItems.reduce(function(sum, item) {
return sum + item.Amount;
}, total);
}
return total;
});
Here, the source is a Knockout observable array and the dxList data source. A value of grand totals is stored in the 'total' variable which is a computed observable depending on 'source'. So, once 'source' is changed, 'total' is re-calculated as well.
var grandTotal = ko.observable(0);
dataSource = new DevExpress.data.DataSource({
// ...
onChanged: function () {
grandTotal(0);
var items = dataSource.items();
for (var i = 0; i < items.length; i++) {
grandTotal(grandTotal() + items[i].Amount());
}
}
});
return {
// ...
grandTotal: grandTotal
};

Partial View not working propely in index view.

I am developing MVC application and using razor syntax.
In this application I am giving comment facility.
I have added a partial view, which loads the comment/Records from DB.
In below image, we can see the comment box which is called run-time for employee index view.
Now as we can see comment box, I called at run-time, which is partial view, but problem is I can add comment for only on first record...after first record that button wont work at all...
anything is missing ?
Is there separate process when we call any partial view run-time and make in action on it ?
See the pic...
Here is the code....
#model PagedList.IPagedList<CRMEntities.Customer>
<link href="../../Content/Paging.css" rel="stylesheet" type="text/css" />
<link href="../../Content/EventEntity.css" rel="stylesheet" type="text/css" />
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")%>" type="text/javascript"></script>
<div id="ListBox">
<div id="ListHeader">
All customers(#Model.TotalItemCount)
</div>
#foreach (var item in Model)
{
<div id="ListContent">
<span class="ContentTitleField">#Html.ActionLink(item.Name, "Details", new { id = item.Id }, new { #style="color:#1A6690;" })</span>
#if (item.Owner != null)
{
<span class="ContentSecondaryField">#Html.ActionLink(item.Owner.FullName, "Details", "Employee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
}
<span class="ContentSecondaryField">#Html.DisplayFor(modelItem => item.Address)</span>
<span id="flagMenus">
#Html.Action("ShowFlag", "Flagging", new { entityId=item.Id, entityType="Customer"})
</span>
#if (item.Opportunities.Count > 0)
{
<span class="FlagOpportunity">#Html.ActionLink("opportunities(" + item.Opportunities.Count + ")", "Index", "Opportunity", new { custid = item.Id }, new { #style = "color:#fff;" })</span>
}
<div style="float:right;">
#Html.Action("SetRate", "Rating", new { entityId = item.Id, rating = item.Rating, entityname = "Customer" })
</div>
<div id="subscribeStatus" style="float:right;">
#Html.Action("ShowSubscribedStatus", "Subscribing", new { entityId = item.Id, entityType = "Customer" })
</div>
<div class="ListLinks">
<span class="ListEditLinks">
<span style="float:left;">#Html.ActionLink("edit", "Edit", new { id = item.Id })</span>
<span class="LinkSeparator"></span>
</span>
<span class="ListAddLinks">
<span style="float:left;">#Html.ActionLink("+opportunity", "Create", "Opportunity", new { custid = item.Id }, null)</span>
<span class="LinkSeparator"></span>
<span>#Ajax.ActionLink("+Comment", null, null, null, new { id = item.Id, #class = "addremark" })</span>
</span>
<div class="RemarkBox"></div>
</div>
<span class="CommentAdd">
</span>
<div class="CommentBlock">
</div>
<span>#Ajax.ActionLink("Add Comment", null, null, null, new { id = item.Id, #class = "addremark" })</span>
</div>
}
<div class="PagingBox">
#Html.Action("CreateLinks", "Pager", new { hasPreviousPage = Model.HasPreviousPage, hasNextPage = Model.HasNextPage, pageNumber = Model.PageNumber, pageCount = Model.PageCount })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.RemarkBox').hide();
$('a.addremark').click(function () {
var url="#Html.Raw(Url.Action("ShowCommentBox", "Comment", new { Id = "idValue", EntityType = "Customer" }))";
url=url.replace("idValue",event.target.id);
$('.RemarkBox').load(url);
$(this).closest('div').find('div.RemarkBox').slideToggle(300);
return false;
});
$("a.pagenumber").click(function () {
var page = 0;
page = parseInt($(this).attr("id"));
$.ajax({
url: '#Url.Action("GetPagedCustomers")',
data: { "page": page },
success: function (data) { $("#customerlist").html(data); }
});
return false;
});
});
</script>
To expand on what Alberto León is saying, the partial page load will not cause the document ready event to fire, so the re-rendered elements will not have the javascript event handlers registered after the first comment is added.
To resolve this, you could put the event registration code into a function, and call this both from the document ready event and the success handler of the AJAX call. Something like this:
function AssignEventHandlers() {
$('a.addremark').click(function () {
....
});
$("a.pagenumber").click(function () {
var page = 0;
page = parseInt($(this).attr("id"));
$.ajax({
url: '#Url.Action("GetPagedCustomers")',
data: { "page": page },
success: function (data) {
$("#customerlist").html(data);
AssignEventHandlers();
}
});
return false;
});
}
$(document).ready(function () {
$('.RemarkBox').hide();
AssignEventHandlers();
}
In success function you need to recall the javascript, or the jquery code that makes the button work. Is an error that taked me a lot of time. Anything uploaded by ajax or any renderpartiAl needs to recall javascript.
$('.RemarkBox').load(url, function() {
//RECALL JAVASCRIPT
});

Categories