Best way to check if a value is in a multiselectlist? - multi-select

Sorry if this is a silly question.
But I've been struggling with this for a while. I want to check if a MultiSelectlist I have contains a particular value. What is the best way to do this? I tried using the contains() function, but it doesn't like it.
Thank you in advance for your help

Apologies for not having done this earlier. New to SO, what can I say!
I wrote the following script to get the values in the MultiSelectList into an array and post it to an action method using Ajax. I then used the Array.Exists() method in the View to check if the string is in the array or not.
var selValuesArr = [];
$("#selColList option").each(function (i, current) {
selValuesArr[i] = $(current).val();
});
Ajax call:
$.ajax({
url: "/Main/Index",
data: { "selValues": selValuesArr }, //JSON.stringify(selValues) },
type: "POST",
success: function (data) {
$("#Grid").html(data);
}
});
And in my View, I have the following function (it takes an int, rather than a string)
#functions {
public bool findColumn(int colId, String[] strArr)
{
String temp = colId.ToString() ;
if (Array.Exists(strArr, s => s.Equals(temp))) {
return true;
} else {
return false;
}
}
}
HTH

Related

dataSource.filter filters ID which is not visible in frontend

Basically, this is my code
applySearchFilter(filterValue: string) {
this.values = filterValue.toString().toLowerCase();
this.dataSource.filter = this.values;
}
with "this.dataSource.filter" I can filter any data out of it, but I want to add an exception to keyId.... See the object below.
my object looks something like this.
{
keyId: "00000000-0000-0000-0000-000000010001",
name: "Test 10",
location: "New York"
}
When I input "10", it filters everything in the dataSource that has a 10. So, not only the name has "10" in it, but the keyId too. I took an hour to realize what this kept happening... and it is because of keyId xD
Allthough I get the whole object with keyId included, keyId is not shown in frontend and should not be search/filter-able. Even if it does not show keyId in frontend, he searches for the object that has that keyid
I am not sure how to fix it right now, since something like this.dataSource.data.name or so does not work...
I'd appreciate if you gals and girls would give me some tips.
Oh and here is where I get my data to that get filtered.
public getObject(): void {
this.service.getObjectMethod().then(data=> {
this.dataSource.data = data;
}, (err: Error) => { console.log(err.message); });
}
i solved this issue using.
public filterData(): void {
if (this.inputValues.trim().length !== 0) {
this.filteredValues = [];
this.dataSource.data.filter(data => {
if (data.name.toLowerCase().includes((this.inputValues).toLowerCase()) ||
data.opensCategory.toLowerCase().includes((this.inputValues).toLowerCase())) {
return true && this.filteredValues.push(data);
}
});
this.dataSource.data = this.filteredValues;
}
}
Use the following code to search.
applySearchFilter(filterValue: string) {
this.dataSource.filterPredicate = function (data: any, filterValue: string) {
return data.name.trim().toLocaleLowerCase().indexOf(filterValue.trim().toLocaleLowerCase()) >= 0;
};
}

Angular 7/Typescript : Create queue/array of methods

I have a requirements that some functions should be called after some method completes execution.
Below is my code of processing the queue.
processQueue() {
while (this.queue.length) {
var item = this.queue.shift();
item.resolve(item.func(item.types));
}
}
This is one of the sample function to push method in queue
getAllValues() {
let promise1 = new Promise((resolve, reject) => {
if (this.isReady) {
resolve(this._getAllValues());
} else {
this.queue.push({
resolve: resolve,
func: this._getAllValues
});
}
});
return promise1;
}
And this is one of the function which will be called on processing the queue
_getAllValues() {
var results = {}, values = this.enumInstance.enumsCache.values;
for (var type in values) {
if (values.hasOwnProperty(type)) {
results[type] = values[type][this.enumInstance.lang];
}
}
return results;
}
The issue i am facing is when i call _getAllValues() directly then i am able to access this.enumInstance.
But when same method is being accessed through processQueue() i am unable to access this.enumInstance. It gives me undefined. I think this is not referred to main class in this case.
So can anyone help me here. How can i resolve this?

AngularJS: promise in a loop

I am unable to do the promise looping.
I make a service call to get list of providers, then for each provider, I make another service call to get a customer.
A provider has 1 or more customers. So eventual list of customer is to be decorated and displayed.
In other format I am trying to achieve:
*serviceA.getProvider(){
foreach(providers){
foreach(provider.customerID){
serviceB.getCustomer(customerId)
}
}
}
.then(
foreach(Customer){
updateTheCustomer;
addUpdatedCustomerToAList
}
displayUpdatedCustomreList();
)*
I have written following code, that isn't working
doTheJob(model: Object) {
let A = [];
let B = [];
let fetchP = function(obj) {
obj.Service1.fetchAllP().then(function (response) {
let P = cloneDeep(response.data);
_.forEach(P, function(prov) {
_.forEach(prov.CIds, function(Id) {
A.push(Id);
});
});
_.forEach(A, function(CId) {
return obj.Service2.getById(CId);//what works is if this statement was: return obj.Service2.getById(A[0]);
//So, clearly, returning promise inside loop isn't working
});
})
.then(function(response) {
B.push(response.data); //This response is undefined
angular.forEach(B, function (value) {
obj.updateAdr(value)
});
obj.dispay(B);
});
};
fetchP(this);
}
forEach don't stop when you use return inside of it, try to use a plain loop instead, why you don't just loop with for ?
_.forEach(A, function(CId) {
return obj.Service2.getById(CId);
}
as stated by #Ze Rubeus if you return inside a callback within a for loop that value will be lost, since it's not returned to the caller.
probably you wanted something like this
return Promise.all(A.map(function(CId){
//collect each promise inside an array that will then be resolved
return obj.Service2.getById(CId);
})

AngularJS: How to create new arrays from JSON response?

I have a function tied to the factory for my controller:
fac.GetDailyCountersList = function () {
return $http.get('/Data/GetDailyCountersList')
}
Inside the controller, here's where the function is called:
$scope.DailyCounters = null;
DailyCounterService.GetDailyCountersList().then(function (d) {
$scope.DailyCounters = d.data;
}, function (error) {
alert('Error!');
});
Based on this, if I were to output the variable on the html page, this would show:
[{"Id":1,"MIDay":"16","MITime":"900","MICounter":0},
{"Id":2,"MIDay":"16","MITime":"915","MICounter":1},
{"Id":3,"MIDay":"16","MITime":"930","MICounter":0},
{"Id":4,"MIDay":"17","MITime":"945","MICounter":0},
{"Id":5,"MIDay":"17","MITime":"1000","MICounter":0},
{"Id":6,"MIDay":"17","MITime":"1015","MICounter":52},
{"Id":7,"MIDay":"18","MITime":"1030","MICounter":2},
{"Id":8,"MIDay":"18","MITime":"1045","MICounter":3},
{"Id":9,"MIDay":"18","MITime":"1100","MICounter":0}]
My question is how to take this data and create other arrays based on one of the properties of the Json data.
For example, how would I put arrays
{"Id":1,"MIDay":"16","MITime":"900","MICounter":0},
{"Id":2,"MIDay":"16","MITime":"915","MICounter":1},
{"Id":3,"MIDay":"16","MITime":"930","MICounter":0}
Into a new array "ArrayDay16"? And the rest into their respective arrays as well.
I was thinking about doing it this way:
var myArray = [];
if (d.data['MIDay'] == '16')
myArray.push(d.data);
But this is incorrect/fails. Any ideas for an efficient solution?
Use the filter function to populate new arrays. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
//This will populate "someArray" with only the data that has MIDAY = 16
DailyCounterService.GetDailyCountersList().then(function (d) {
$scope.someArray = d.data.filter(function(ele) {
return ele.MIDAY === '16';
});
}
You can use the filter function:
var daySixteen = data.filter(function (d) { return d.MIDay === "16"; });
you can try the next:
d.data.foreach(function(item){
if(item.MIDay == 16)
myArray.push(d.data);
});
If you want to be efficient you should do this on the back end with constraint(s). It's not the browsers job.
Although, if you still want it to filter it on the front end you could use the filter-function with some lamdba expressions
var newList = oldList.filter(i => i["MIDay"] == "16");

getting an error using breeze - The 'structuralTypeName' parameter must be a 'string'

I am going through John Papa's SPA course on pluralsight and I am running into error that say The 'structuralTypeName' parameter must be a 'string' while using breeze. Here is the actual error that is being thrown
The code that is generating this error is metadataStore.getEntityType:
function extendMetadata() { names
var metadataStore = manager.metadataStore;
var types = metadataStore.getEntityType();
types.forEach(function(type) {
if (type instanceof breeze.EntityType) {
Set(type.shortName, type)
}
});
function set(resourceName, entityName) {
metadataStore.setEntityTypeForResourceName(resourceName, entityNames);
}
it is called by my prime function.
function prime() {
if (primePromise) return primePromise //if primePromise was loaded before, just return it
primePromise = $q.all([getLookups()])
.then(extendMetadata)
.then(success);
return primePromise;
function success() {
setLookups();
log('Primed the data');
}
I'm unsure what the problem is with the breeze call. Any insight into how to fix this? Thanks for your help community.
Nick
Here is the lookups query info:
function setLookups() {
var entityNames = {
personnel: 'Personnel',
cto: 'Cto',
kkeys: 'Kkey',
promotion: 'Promotion',
loa: 'Loa'
};
service.lookupCachedData = {
ctos: _getAllLocal(entityNames.cto, 'ctodate' )
kkeys: _getAllLocal(entityNames.kkeys, 'keystamp'),
promotions: _getAllLocal(entityNames.promotion, 'pdate'),
loas: _getAllLocal(entityNames.loa, 'lstrdte')
}
}
function _getAllLocal(resource, ordering) {
return EntityQuery.from(resource)
.orderBy(ordering)
.using(manager)
.executeLocally();
}
function getLookups() {
return EntityQuery.from('Lookups')
using(manager).execute()
.then(querySucceeded, _queryFailed)
function querySucceeded(data) {
log('Retrieved [Lookups] from remote data source', data, true);
return true;
}
}
function _queryFailed(error) {
var msg = config.appErrorPrefix + 'Error retrieving data from entityquery' + error.message;
logError(msg, error);
throw error;
}
You have to pass in a string to getEntityType. Sorry I missed that the first time through.
metadataStore.getEntityType('cto');
Also you are going to blow up when you are trying to call Set() function but the functions name is set() and also set is probably a keyword you aren't trying to override.

Resources