DataTable replicating rows - javascript

I have a panel where I take data from a view in database, and show them. The data are being showed but it is being replicated 3 times, I mean, each row apears 3 times in my table (panel).
When I use my filters, the data apears only one time though, as it should be.
I thought that I was calling my function "criarDataTables()" 3 times, but this is not the case.
This is in my Index.cshtml:
#section Scripts{
#Scripts.Render("~/bundles/typeahead")
#Scripts.Render("~/bundles/datatables")
#Scripts.Render("~/Scripts/js/bootstrap-datapicker.js")
#Scripts.Render("~/Scripts/js/bootstrap-datepicker.pt-BR.js")
#Scripts.Render("~/Scripts/jQuery-Mask/jquery.mask.min.js")
<script type="text/javascript">
var tbPainelTriagem;
var reload = false;
function criarDataTables() {
tbPainelTriagem = $("#tb-triagem").DataTable({
searching: false,
processing: true,
serverSide: true,
ajax: {
url: "/PainelTriagem/ListaPainelTriagem",
type: "POST",
data: {
customSearch: {
[...]
}
}
},
columns: [
{ data: "ID_VIEW" },
{ data: "TIPO" },
[...]
],
columnDefs: [
],
drawCallback: function (settings, json) {
$("#frm-filtro :input").prop("disabled", false);
}
});
}
$(document).ready(function () {
var listaDs;
$('#dsUnidIntField').attr("autocomplete", "off");
$('#dsUnidIntField').typeahead({
name: 'resultDs',
limit: 200,
minLength: 0,
source: function (query, process) {
itens = [];
listaDs = {};
$.post('/PainelTriagem/DsAutocomplete', { query: query }, function (data) {
$.each(data, function (i, item) {
listaDs[item.Nome] = item;
itens.push(item.Nome);
});
process(itens);
});
},
updater: function (item) {
var ds = listaDs[item];
$('#ID_VIEW', '#frm-filtro').val(ds);
return ds.Nome;
}
});
criarDataTables();
})
</script>
}
[...]
<table id="tb-triagem" class="table table-striped table-bordered dataTableLayout">
<thead>
<tr>
<th>ID View</th>
<th>Tipo</th>
[...]
</tr>
</thead>
</table>
This is in my PainelTriagemController.cs
using [...]
namespace PainelMV.Controllers
{
public class PainelTriagemController : Controller
{
[...]
[HttpPost]
public ActionResult ListaPainelTriagem(HCDataTableRequest<PainelTriagem> dataTableRequest)
{
try
{
HCDataTableResponse<PainelTriagemViewModel> dataTable = MyPainelTriagemManager
.ToList(dataTableRequest).CastViewModel(x => new PainelTriagemViewModel
{
ID_VIEW = x.ID_VIEW,
TIPO = x.TIPO == null ? " - " : x.TIPO.ToString(),
[...]
});
return Json(dataTable);
}
catch(Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
}
}
And this is in my PainelTriagemStore.cs
using [...]
namespace PainelMV.Data.Store
{
public class PainelTriagemStore : BaseStore<PainelTriagem, AppContext>
{
public PainelTriagemStore(AppContext context): base(context) { }
public HCDataTableResponse<PainelTriagem> ToList(HCDataTableRequest<PainelTriagem> dataTableRequest)
{
try
{
HCDataTableResponse<PainelTriagem> response = new HCDataTableResponse<PainelTriagem>();
var qr = _context.PainelTriagem.AsQueryable();
response.recordsTotal = qr.Count();
int? tipo = dataTableRequest.GetCustomSearchInt("tipo");
string nmPaciente = dataTableRequest.GetCustomSearchString("nmPaciente");
[...]
if (tipo != null)
{
qr = qr.Where(x => x.TIPO == tipo);
}
[...]
response.recordsFiltered = qr.Count();
qr = qr.OrderAndPaging(dataTableRequest);
response.data = qr.ToList();
return response;
}
catch(Exception ex)
{
throw ex;
}
}
}
}

Related

Unable to cast object of type 'System.String' to type 'System.Boolean .Net Core MVC

I refer this tutorial https://github.com/bhrugen/AppointmentScheduler
I did same code but I'm not able to show Get Calendar Data when I running it, It's shows error - Unable to cast object of type 'System.String' to type 'System.Boolean.
My Code is :-
AppointmentApiController.cs :
[HttpGet]
[Route("GetCalendarData")]
public IActionResult GetCalendarData(string doctorId)
{
CommonResponse<List<AppointmentVM>> commonResponse = new CommonResponse<List<AppointmentVM>>();
try
{
if (role == Helper.Patient)
{
commonResponse.dataenum = _appointmentService.PatientsEventsById(loginUserId);
commonResponse.status = Helper.success_code;
}
else if (role == Helper.Doctor)
{
commonResponse.dataenum = _appointmentService.DoctorsEventsById(loginUserId);
commonResponse.status = Helper.success_code;
}
else
{
commonResponse.dataenum = _appointmentService.DoctorsEventsById(doctorId);
commonResponse.status = Helper.success_code;
}
}
catch (Exception e)
{
commonResponse.message = e.Message;
commonResponse.status = Helper.failure_code;
}
return Ok(commonResponse);
}
Script.js :
var routeURL = location.protocol + "//" + location.host;
$(document).ready(function () {
$("#appointmentDate").kendoDateTimePicker({
value: new Date(),
dateInput: false
});
InitializeCalendar();
});
var calendar;
function InitializeCalendar() {
try {
var calendarEl = document.getElementById('calendar');
if (calendarEl != null) {
calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
headerToolbar: {
left: 'prev,next,today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
selectable: true,
editable: false,
select: function (event) {
onShowModal(event, null);
},
eventDisplay:'block',
events: function (frtch, successCallback, failureCallback) {
$.ajax({
url: routeURL + '/api/Appointment/GetCalendarData?doctorId=' + $("#doctorId").val(),
type: 'GET',
dataType: 'JSON',
success: function (response) {
var events = [];
if (response.status === 1) {
$.each(response.dataenum, function (i, data) {
events.push({
title: data.title,
description: data.description,
start: data.startDate,
end: data.endDate,
backgroundColor: "#162466",
textColor: "white",
id: data.id
});
})
}
successCallback(events);
},
error: function (xhr) {
$.notify("Error", "error");
}
});
},
eventClick: function (info) {
getEventDetailsByEventId(info.event);
}
});
calendar.render();
}
}
catch (e) {
alert(e);
}
}
AppointmentService.cs :
public List<AppointmentVM> DoctorsEventsById(string doctorId)
{
return _db.Appointments.Where(x => x.DoctorId == doctorId).ToList().Select(c => new AppointmentVM()
{
Id = c.Id,
Description = c.Description,
StartDate = c.StartDate.ToString("yyyy-MM-dd HH:mm:ss"),
EndDate = c.EndDate.ToString("yyyy-MM-dd HH:mm:ss"),
Title = c.Title,
Duration = c.Duration,
IsDoctorApproved = c.IsDoctorApproved
}).ToList();
}
IAppointmentService.cs :
public List<AppointmentVM> DoctorsEventsById(string doctorId);
Unable to cast object of type 'System.String' to type 'System.Boolean.
You need to make sure the type of IsDoctorApproved in AppointmentVM is bool:
public class AppointmentVM
{
public bool IsDoctorApproved {get;set;}
}
Also,you need to make sure the type of IsDoctorApproved in your database is bool.

DataTables warning: table id=DimStatus - Requested unknown parameter 'Code' for row 0, column 0,when initialize datatable

I want to show my data in datatable but I get the above error.
My Table Property:
[Table("DimStatus", Schema = "dmg")]
public class PolicyState
{
[Key]
public int Code { get; set; }
public string Title { get; set; }
}
My Api :
[Route("api/[controller]/[action]")]
[ApiController]
public class ReportController : Controller
{
private ICommonServices _CommonService;
public ReportController(ICommonServices CommonService)
{
_CommonService = CommonService;
}
// GET
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult GetPolicyState()
{
try
{
var draw = Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var sortColumn = Request.Form["columns[" + Request.Form["order[0]
[column]"].FirstOrDefault() +
"][name]"].FirstOrDefault();
var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
var searchValue = Request.Form["search[value]"].FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var PolicyData = (from tempcustomer in _CommonService.GetPolicyState() select tempcustomer);
//var PolicyData = _CommonService.GetPolicyState();
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
{
PolicyData = PolicyData.OrderBy(sortColumn + " " + sortColumnDirection);
}
if (!string.IsNullOrEmpty(searchValue))
{
PolicyData = PolicyData.Where(m => m.Title.Contains(searchValue));
}
recordsTotal = PolicyData.Count();
var data = PolicyData.Skip(skip).Take(pageSize).ToList();
var jsonData = new
{
draw = draw,
recordsFiltered = recordsTotal,
recordsTotal = recordsTotal,
data = data
};
var testd = jsonData;
return Ok(jsonData);
}
catch (Exception ex)
{
throw;
}
}
}
and last my index.cshtml:
<link rel="stylesheet" type="text/css"
href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.css">
<div class="container">
<br />
<div style="width:90%; margin:0 auto;">
<table id="DimStatus" class="table table-striped table-bordered dt-responsive nowrap"
width="100%" cellspacing="0">
<thead>
<tr>
<th>Code</th>
<th>Title</th>
<th>asdf</th>
</tr>
</thead>
</table>
</div>
</div>
#section Scripts
{
<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function () {
dataTable = $('#DimStatus').dataTable({
serverSide: true,
processing: true,
//searchDelay: 500,
pageLength: 10,
infoFiltered: true,
orderMulti: false,
"ajax": {
"url": "/api/Report/GetPolicyState",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Code", "name": "Code", "autoWidth": true },
{ "data": "Title", "name": "Title", "autoWidth": true },
{
"render": function (data, row) {
return "<a href='#' class='btn btn-danger' onclick=DeleteCustomer('" +
row.Code + "'); >Details</a>";
}
},
]
});
});
would if anybody know the issue help me solve it. thank you in advanced.
Your error clearly states that your returning data does not have any property name "Code". Make sure that the data structure your are returning contains property name "Code" as you are processing on PolicyData class and not PolicyState class that you have showed in the sample code.

Reload DataTable on Every Page Refresh

All I am trying to do is that I want to refresh my DataTable when the page is relaoded/refreshed. Right now on refreshing the page it retains its data. My application is using ASP.Net MVC tech.
Here is my Data Table and relevant functions:
$(document).ready(function () {
//debugger;
var table = $('#user_session_center_grid').DataTable({
"searching": false,
"colReorder": true,
"lengthChange": false,
"processing": true,
"serverSide": true,
"autoWidth": false,
"ajax": {
cache: false,
url: "#Url.Action("GetUserSessionHistory", "LoggedIn")",
type: 'POST',
data: function (data) {
data.SortBy = 'Month';
data.FromDate = "";
data.ToDate = "";
data.userSearch = $('#userSearch').val();
if (event) {
var objDtFilter = event.target;
if ($(objDtFilter).hasClass('dtFilter')) {
data.FromDate = event.target.getAttribute('fromdt');
data.ToDate = event.target.getAttribute('todt');
}
if ($(objDtFilter).hasClass('dtSort'))
data.SortBy = event.target.getAttribute('sort');
if ($(objDtFilter).hasClass('UserTypeFilter'))
data.value1 = event.target.getAttribute('value');
console.log(data.value1);
}
},
},
"language": {
oPaginate: {
sNext: '<i class="fa fa-chevron-right"></i>',
sPrevious: '<i class="fa fa-chevron-left"></i>',
sFirst: '<i class="fa fa-chevron-right"></i>',
sLast: '<i class="fa fa fa-chevron-left"></i>'
}
},
"columns": [
{
data: null,
class: "userName",
render: function (data, type, row) {
return "<div>" + data.FirstName + " " + data.LastName + "</div></td>";
}
},
{
data: null,
class: "startDate",
render: function (data, type, row) {
var parsedDate = JSON.parse(JSON.stringify(data.StartTime), ToJavaScriptDate);
return "<div>" + parsedDate + "</div></td>";
}
},
//{ 'data': 'User_ID' },
//{ 'data': 'FirstName' },
//{ 'data': 'LastName' },
//{ 'data': 'StartTime' },
],
});
table.on('draw', function () {
var widthofPagination = $('.dataTables_paginate.paging_simple_numbers').width() + 25;
$('#user_session_center_grid_info').css({ width: 'calc(100% - ' + widthofPagination + 'px)' });
});
$("#date_filter_ul.dropdown-menu li a").click(function () {
//debugger;
$('#date_filter_ul').removeClass('show');
$(this).closest('#CategoryFilter').find('.csp-select > span').text("Duration:" + $(this).text());
$('#user_session_center_grid').DataTable().ajax.reload();
});
$("#user_session_center_status_ul.dropdown-menu li a").click(function () {
$('#user_session_center_status_ul').removeClass('open');
$(this).closest('#StatusFilter').find('.csp-select > span').text($(this).text());
$('#user_session_center_grid').DataTable().ajax.reload();
});
});
Here are my controller functions:
public ActionResult UserSessionCenter()
{
if (Session["selectedCustomer"] == null)
{
Session["selectedCustomer"] = 9;
}
int customerId = (int)Session["selectedCustomer"];
var model = new UserSessionHistory();
var daccess = new ApplicationCommon.Ado.SqlDataAccess();
var customerNamesDt = daccess.GetUserNames(customerId);
var customerList = new List<UserSessionData>();
for (var i = 0; i < customerNamesDt.Rows.Count; i++)
{
var userinfo = new UserSessionData();
userinfo.CustomerId = customerNamesDt?.Rows[i]["Customer_Id"].ToString() ?? "";
userinfo.CustomerName = customerNamesDt?.Rows[i]["Customer_Name"].ToString() ?? "";
userinfo.UserId = customerNamesDt?.Rows[i]["User_ID"].ToString() ?? "";
userinfo.UserName = customerNamesDt?.Rows[i]["UserName"].ToString() ?? "";
customerList.Add(userinfo);
}
model.UserInfoList = customerList;
return View(model);
}
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult GetUserSessionHistory()
{
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
if (Request["value1"] != null)
Session["userId"] = Request["value1"];
int pageSize = length != null ? Convert.ToInt32(length) : 0;
try
{
var UserID = Convert.ToInt32(Session["userId"]);
var filterModel = new FilterSessionHistoryModel();
filterModel.UserID = UserID;
filterModel.Skip = int.Parse(start);
filterModel.Take = int.Parse(length);
var fromDate = Request["FromDate"];
var toDate = Request["ToDate"];
filterModel.userSearch = Request["userSearch"];
if (!string.IsNullOrEmpty(fromDate) && !string.IsNullOrEmpty(toDate))
{
filterModel.DateFrom = fromDate;
filterModel.DateTo = toDate;
}
UserService userService = new UserService();
List<ADM_User_Session_History_Result> SessionList = userService.ADM_User_Session_History(filterModel);
int? numberOfRecords = 0;
if(SessionList.Count>0) {
numberOfRecords=SessionList[0].NumberOfRecords;
}
return Json(new { draw = draw, recordsFiltered = (int)numberOfRecords, recordsTotal = (int)numberOfRecords, data = SessionList }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
CustomLogging.LogMessage(ex.Message + "/r/n" + ex.Source + "/r/n" + ex.StackTrace, LogType.Error);
return this.GetJSONObject(false, ex.Message.ToString());
}
}
The hierarchy is like this.
1. The Admin user can use any customer
2. One customer can have many users
3. The table shows the time of log in of the user selected.
The problem is that the list through which the Admin can change the Customer is in the top nav present in _Layout.cshtml where as this data table is in another view. The data changes fine while cahanging the user but I need it to reload or get empty when the customer is changed.
old browsers like 'explorer' keep caching the info from a first ajax call,
you can try to set the cash flag to false and the table will be updated each time
function ReLoadTable() {
$.ajax({
cache: false,
url: 'Your URL',
type: 'POST',
in controller put this attribute
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class HomeController : Controller
{
finally in your Global.asax file add this function
protected void Application_PreSendRequestHeaders(Object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetAllowResponseInBrowserHistory(false);
}

Knockout children of children loading/options in MVC

I have problem loading children to my option list.
I create an order but I cannot Edit. It will not load the dropdownlists.
My goal is when I press Edit on an order.
It will have selected the current product in the dropdownlist on the orderitem.
And I want to put the price from Product Model to the view(when choosing an item from dropdownlist)
Is there any other way to populate the dropdownlist?
I will upload pictures.
Here is my code javascript code.
var Products = [];
//fetch categories from database
function LoadProducts(element) {
if (Products.length == 0) {
//ajax function for fetch data
$.ajax({
type: "GET",
url: '/Sales/GetProducts',
success: function (data) {
Products = data;
//render catagory
renderProducts(element);
}
})
}
else {
alert("else");
//render catagory to the element
renderProducts(element);
}
}
function renderProducts(element) {
var $ele = $(element);
$ele.empty();
$ele.append($('<option/>').val('0').text('Select'));
$.each(Products, function (i, val) {
$ele.append($('<option/>').val(val.ProductId).text(val.ProductName));
})
}
var Seats = [];
//fetch categories from database
function LoadSeats(element) {
if (Seats.length == 0) {
//ajax function for fetch data
$.ajax({
type: "GET",
url: '/Sales/GetSeats',
success: function (data) {
Seats = data;
//render catagory
renderSeats(element);
}
})
}
else {
//render catagory to the element
renderSeats(element);
}
}
function renderSeats(element) {
var $ele = $(element);
$ele.empty();
$ele.append($('<option/>').val('0').text('Select'));
$.each(Seats, function (i, val) {
$ele.append($('<option/>').val(val.SeatId).text(val.SeatPlace));
})
}
var Employees = [];
//fetch categories from database
function LoadEmployees(element) {
if (Employees.length == 0) {
//ajax function for fetch data
$.ajax({
type: "GET",
url: '/Sales/GetEmployees',
success: function (data) {
Employees = data;
//render catagory
renderEmployees(element);
}
})
}
else {
//render catagory to the element
renderEmployees(element);
}
}
function renderEmployees(element) {
var $ele = $(element);
$ele.empty();
$ele.append($('<option/>').val('0').text('Select'));
$.each(Employees, function (i, val) {
$ele.append($('<option/>').val(val.EmployeeId).text(val.EmployeeName));
})
}
var PaymentMethods = [];
//fetch categories from database
function LoadPaymentMethods(element) {
if (PaymentMethods.length == 0) {
//ajax function for fetch data
$.ajax({
type: "GET",
url: '/Sales/GetPaymentMethods',
success: function (data) {
PaymentMethods = data;
//render catagory
renderPaymentMethods(element);
}
})
}
else {
//render catagory to the element
renderPaymentMethods(element);
}
}
function renderPaymentMethods(element) {
var $ele = $(element);
$ele.empty();
$ele.append($('<option/>').val('0').text('Select'));
$.each
(PaymentMethods, function (i, val) {
$ele.append
($('<option/>')
.val(val.PaymentMethodId)
.text(val.PaymentMethodType));
})
}
var ObjectState = {
Unchanged: 0,
Added: 1,
Modified: 2,
Deleted: 3
};
LoadProducts($('#productCategory'));
var salesOrderItemMapping = {
'SalesOrderItems': {
key: function (salesOrderItem) {
// alert("Salesorderitem mapping key");
return ko.utils.unwrapObservable(salesOrderItem.SalesOrderItemId);
},
create: function (options) {
console.log(options);
return new SalesOrderItemViewModel(options.data);
}
}
};
//var productItemMapping = {
// 'Products': {
// key: function(product) {
// return ko.utils.unwrapObservable(product.ProductId);
// },
// create: function(options) {
// return new SalesOrderViewModel(options.data);
// }
// }
//};
// ko.mapping.fromJS(data, productItemMapping, SalesOrderViewModel);
SalesOrderItemViewModel = function (data) {
//alert("salesorder item view"); // funkade
var self = this;
ko.mapping.fromJS(data, salesOrderItemMapping, self);
//dd: ko.observableArray(Products);
self.itemss = ko.observableArray(Products);
self.selectedItem = ko.observable(Products.ProductId);
//self.product1 = ko.observableArray(Products());
//self.dd = ko.observableArray(function() {
// //data.ProductId = data.Products.ProductId;
// return self.Products();
//});
self.flagSalesOrderAsEdited = function() {
if (self.ObjectState() !== ObjectState.Added) {
self.ObjectState(ObjectState.Modified);
}
// alert("salesorder item view if");
return true;
};
};
SalesOrderViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, salesOrderItemMapping, self);
//alert("salesorder view model"); // funkade
self.save = function () {
$.ajax({
url: "/Sales/Save/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data) {
if (data.salesOrderViewModel !== null)
ko.mapping.fromJS(data.salesOrderViewModel, {}, self);
if (data.newLocation !== null)
window.location = data.newLocation;
}
});
},
self.flagSalesOrderAsEdited = function () {
if (self.ObjectState() !== ObjectState.Added) {
self.ObjectState(ObjectState.Modified);
}
return true;
},
self.deleteSalesOrderItem = function(salesOrderItem) {
self.SalesOrderItems.remove(this);
if (salesOrderItem.SalesOrderItemId() > 0 &&
self.SalesOrderItemsToDelete.indexOf
(salesOrderItem.SalesOrderItemId()) === -1)
self.SalesOrderItemToDelete.push(SalesOrderItemId());
}
self.addSalesOrderItem = function () {
// alert(" add salesorder item"); // funkade
var salesOrderItem = new SalesOrderItemViewModel(
{ SalesOrderItemId: 0, ProductId: 1, Quantity: 1,
ObjectState: ObjectState.Added });
self.SalesOrderItems.push(salesOrderItem);
};
};
//UnitPrice: 1
LoadSeats($('#SeatId'));
LoadEmployees($('#EmployeeId'));
LoadPaymentMethods($('#PaymentMethodId'));
Here is my Edit Partial view.
<table class="table table-striped">
<tr>
<th>Product Name</th>
<th>Quantity</th>
#*<th>Unit Price</th>*#
<th><button class="btn btn-info btn-xs"
data-bind="click: addSalesOrderItem">Add</button></th>
</tr>
<tbody data-bind="foreach: SalesOrderItems">
<tr>
<td>
#*<select id="productCategory" class="pc form-control"
data-bind="value: ProductId">
<option>Select</option>
</select>*#
#*<select data-bind="options: $parent.product1,
optionsText: 'ProductName', optionsValue: 'ProductId',
value: ProductId"></select>*#
<select data-bind=
"options: itemss, optionsText: 'ProductName',
value: ProductId, optionsValue: 'ProductId',
selectedOption: selectedOption"> </select>
</td>
#*<td class="form-group">
<input class="form-control input-sm" data-bind="value: ProductId" /></td>*#
<td class="form-group">
<input class="form-control input-sm" data-bind="value: Quantity"/></td>
#*<td class="form-group">
<input class="form-control input-sm" data- bind="text: UnitPrice"/></td>*#
<td class="form-group">Delete</td>
</tr>
</tbody>
</table>
Here it is when I create
Here it is when I Edit an order
And I get this problem when I save
I have problem loading children to my option list.
I create an order but I cannot Edit. It will not load the dropdownlists.
My goal is when I press Edit on an order.
It will have selected the current product in the dropdownlist on the orderitem.
And I want to put the price from Product Model to the view(when choosing an item from dropdownlist)
I will upload pictures.
I would like a road to follow. I am new to knockout/mvc and I cant find examples on mapping. I would appriatiate any feedpack or steps I can use.
If you need more from me, just write.
Thank you!!!
This is my Create View btw(how it is linked to knockout)
#model TheSolution.Domain.viewModels.SalesOrderViewModel
#using System.Web.Script.Serialization
#{
ViewBag.Title = "Create Sales Order";
}
#{
string data = new JavaScriptSerializer().Serialize(Model);
}
#section scripts
{
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="~/Scripts/salesorderviewmodel.js"></script>
<script type="text/javascript">
var salesOrderViewModel = new SalesOrderViewModel(#Html.Raw(data));
ko.applyBindings(salesOrderViewModel);
</script>
}
#Html.Partial("_EditSalesOrder");
Since Ajax is loading asyc. It didnt had the time to load.
To fix the Edit problem with loading my Dropdown list. I used an ajaxStop in the Views(Create and Edit) It waits until ajax have loaded before GET the view
Here is the code
$(document).ajaxStop(function (event, request, settings) {
var salesOrderViewModel = new SalesOrderViewModel(#Html.Raw(data));
ko.applyBindings(salesOrderViewModel);
});
And with the price I had to do an ko ArrayFirst to match the ProductId observable with the ProductId in the Products Array(the one I loaded with Ajax)
And it would return the UnitPrice value from that row in the model.
This is how it looks like.
self.findItem = function () {
console.log(self.itemss().length);
var thePrice = ko.utils.arrayFirst(self.itemss(), function (item) {
return item.ProductId === self.ProductId();
}).UnitPrice;
console.log(thePrice);
return thePrice * self.Quantity();
}

Populate dropdown values from database using javascript service

Hello I am new to AngularJS and I am trying to populate values for my column dropdown in a ui grid. Currently it just displays undefined for the whole list.
Here is my column definition:
{ field: "FullName", displayName: "Employee", editableCellTemplate: 'ui-grid/dropdownEditor', validators: { required: true }, minWidth: 150, width: "25%", cellFilter: 'mapEmployee', editDropdownIdLabel: 'Value', editDropdownValueLabel: 'Text', editDropdownOptionsArray: dataService.getEmployees() },
Here is my service function:
function getEmployees() {
return $.ajax({
url: '/EmployeeSkills/GetEmployees',
type: 'POST',
dataType: "json",
success: getEmployeesComplete,
error: getEmployeesFailed
});
function getEmployeesComplete(r) {
return r;
}
function getEmployeesFailed(e) {
$log.warn("Failed to get employees. " + e.data);
return $q.reject(e);
}
}
Here is my Controller method:
[HttpPost]
public JsonResult GetEmployees()
{
try
{
List<string> tecPosition = new List<string>() { "SUB", "" };
IEnumerable<SelectListItem> Employees = db.Employees.Where(x => tecPosition.Contains(x.JobPosition) && x.Active).Select(c => new SelectListItem
{
Value = c.EmployeeNumber.ToString(),
Text = c.FullName
});
return Json(new SelectList(Employees), JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return null;
}
}
Here is my ui grid:
<div class="row">
<div class="grid" ui-grid="gridOptions"
ui-grid-pagination
ui-grid-selection
ui-grid-edit
ui-grid-row-edit
ui-grid-validate
ui-grid-exporter
ui-grid-cellNav
style="height: 500px;">
</div>
</div>
Any help would be greatly appreciated. It does make it to my Controller method and appears to be working but in the display it just list undefined over and over. Thanks
I had to add a cellFilter of griddropdown:editDropdownOptionsArray:editDropdownIdLabel:editDropdownValueLabel‌​:row.entity.employees.fullname. And write a filter to map the value to the id when the cell loses focus.
.filter('griddropdown', function () {
return function (input, map, idField, valueField, initial) {
if (typeof map !== "undefined") {
for (var i = 0; i < map.length; i++) {
if (map[i][idField] == input) {
return map[i][valueField];
}
}
} else if (initial) {
return initial;
}
return input;
};

Categories