MVC ViewBag Two Dimentional Array - How to access elements from controller - arrays

I have a simple MVC C# controller with 2 dimention array.
ViewBag.states = new SelectList(db.states, "state_code", "state_zone");
If state_code = "FL", I want to get its state_zone value in the controller
I tried:
int newZone = ViewBag.states["FL"].state_zone
but I get error:
Cannot apply indexing with [] to an expression of type 'System.Web.Mvc.SelectList'
Any ideas?

Since ViewBag.states is dynamic property, you can't use indexer of SelectList against it because state_zone already stored inside Text property:
int newZone = ViewBag.states["FL"].state_zone;
Also this declaration seems possible but may throwing indexing error as described in comment:
var zone = ViewBag.states as SelectList;
int newZone = Convert.ToInt32(zone.Items[0].Text); // error: 'cannot apply indexing with [] to an expression of type 'System.Collections.IEnumerable'
To use SelectList item indexer inside ViewBag object, you need to convert it into SelectList first, then use LINQ methods to reveal its value:
var zone = ViewBag.states as SelectList;
int newZone = Convert.ToInt32(zone.Skip(n).First().Text); // n = any index number
// alternative:
int newZone = Convert.ToInt32(zone.Where(p => p.Value == "[any_value]").First().Text);
Similar issue:
Get a text item from an c# SelectList

Related

How to push object into an array? in Angular 7

I am pushing an object into an array but cannot do it?
I'm doing it like this
this.passData = this.tribeForm.value;
var id = {"tribe_id": 1}
this.passData.push(id)
This is the value in the tribeForm
I also tried
var id = {tribe_id: 1}
and
this.passData.splice(0,0, id)
and
this.passData = Array.prototype.slice(id)
and
this.passData.concat(id)
but it all ends up with
TypeError: this.passData.push/splice/concat is not a function
The question is not that clear, But I understood you are manipulating form data, value of form data returns an Object, Not an array. Objects in JavaScript are represented as key-value pairs, (or attribute-value) pairs.
Example :
var object = {
name : "Jhon",
grade : 12,
gpa : 8.12
}
It is just a collection of key-value pairs, push(), concat() and other methods are supported only for Arrays not for Objects. You can achieve whatever you want simply by creating a new key/attribute and assigning the value to it.
this.passData = this.tribeForm.value
this.passData['tribe_id'] = 1
//or, Objects can also contain nested object
this.passData['someKey'] = {'tribe_id' : 1}
You can create an empty array and push objects to it
Example :
var exampleArray = []
exampleArray.push({'tribe_id' : 1})
Now, it works because exampleArray is an Array not JS object.
Thanks for A2A
First, you need to understand the error:
TypeError: this.passData.push/splice/concat is not a function
Push/splice/concat is functions for Array and because of that the console is yelling at you that the passData is not an Array.
Make sure your passData is an Array and you will able to do so.

How to use Array in JEXL?

Using JEXL, I am trying to initialize array and than adding elements into it, however below code gives me 'unsolvable property '0' error.
var abc=[];
abc[0]=5;
1) How can I initialize empty array and keep adding values in it?
2) Can I use it like List, where I do not need to specify size at the time of initialization ?
in JEXL syntax you can initialize objects with new function.
Other option is to add to context arraylist:
This is a working example with jexl2:
JexlEngine jexl = new JexlEngine();
String jexlExp = "var abc=new(\"java.util.ArrayList\", 1);abc[0]=5";
Expression e = jexl.createExpression( jexlExp );
List<Integer> abc = new ArrayList<>(1);
JexlContext jc = new MapContext();
//jc.set("abc", abc ); second option to add arraylist to context
Object o = e.evaluate(jc);
In JEXL, the syntax [] creates a Java array, not a List. As an array, it has a fixed size, so you cannot add values to it. However, JEXL 3.2 has a new syntax for creating an ArrayList literal. Basically, you add ... as the final element.
So in JEXL 3.2, your example could be written as:
var abc=[...];
abc.add(5);
See the JEXL literal syntax reference for more information.

How to convert BasicDBList to List<T> using MappingMongoConverter (spring-data-mongo)?

Executing below code returns the result that contains the element of type hashmap instead of type T (the basicDBList coming from mongoDB does not have "_class" attribute:
com.mongodb.BasicDBList basicDBList = // output of mongoDB query;
List<T> result = mongoOperations.getConverter().read(List.class, basicDbList);
Is there any way to provide type information of List to the read method ?
Not exactly clear what you're trying to achieve, but if you acquired your BasicDBList by calling the getRawResults().get("result") of an AggregationResults instance, you can instead call getMappedResults:
Aggregation aggregation = Aggregation.newAggregation(...);
AggregationResults<Foo> r = mongoTemplate.aggregate(aggregation, "foos", Foo.class);
List<Foo> foos = r.getMappedResults();

WPF list<t> sort

my first post here.
i have a list"<"frameworkelement> that i'm populating with a select process. each frameworkelement has a uid that holds its ZOrder.
i need to sort these by the ZOrder from lowest to highest. i can get this using a listbox and adding the Uid's like this:
//Add Object Uid's
ListBox lstTempOrder = new ListBox();
foreach(FrameworkElement feObject in MainWindow.Data.SelectedObjects)
{
lstTempOrder.Items.Add(feObject.Uid);
}
//Reorder from 0 to above of the ZIndexes
lstTempOrder.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("", System.ComponentModel.ListSortDirection.Ascending));
but i need to do this with a List"<"FrameWorkElement> and Sort.
Here is the code where i populate the List"<"T> (SelectedObjects and CopyObjectsCollections are List"<"FrameWorkElement>" lists.
foreach(FrameworkElement feObject in MainWindow.Data.SelectedObjects)
{
MainWindow.Data.CopyObjectsCollection.Add(feObject);
}
i've looked at CollectionViewSource and IComparer but i can't really make any sense of it.
I might have miss-read your question, but if you just want to sort your List<T>, then why don't you just use the LinQ OrderBy method?
MainWindow.Data.CopyObjectsCollection =
MainWindow.Data.CopyObjectsCollection.OrderBy(f => f.Uid).ToList();
If that sorts it the wrong way round for your requirements, then you can use this:
MainWindow.Data.CopyObjectsCollection =
MainWindow.Data.CopyObjectsCollection.OrderByDescending(f => f.Uid).ToList();
UPDATE >>>
OrderBy is a LinQ extension method. Add using System.Linq; at the top of your class to use it. f relates to an instance of your FrameworkElement object. The above lambda expression basically means 'sort using the Uid property values'.
UPDATE 2 >>>
The OrderBy method does not alter the original collection... that is why my example sets the collection to the result of the OrderBy method. See this basic example:
List<FrameworkElement> elements = new List<FrameworkElement>();
elements.Add(new FrameworkElement() { Uid = "Object1003-1" });
elements.Add(new FrameworkElement() { Uid = "Object1002-2" });
elements.Add(new FrameworkElement() { Uid = "Object1002-1" });
elements.Add(new FrameworkElement() { Uid = "Object1001-1" });
elements.Add(new FrameworkElement() { Uid = "Object1001-3" });
elements.Add(new FrameworkElement() { Uid = "Object1001-2" });
string result = string.Join(", ", elements.Select(f => f.Uid));
elements = elements.OrderBy(f => f.Uid).ToList();
string orderedResult = string.Join(", ", elements.Select(f => f.Uid));
By comparing the values of result and orderedResult you can see that this orders them perfectly.
UPDATE 3 (and hopefully the LAST one) >>>
Dude, you need to learn about Lambda expressions... take a look at the Lambda Expressions (C# Programming Guide) page at MSDN for more information.
elements = elements.OrderBy(f => f.Uid).ToList();
The f in this Lambda expression is declared in this expression before the '=>'. It is fairly standard to name these parameters with one letter like Exceptions, but we could name it anything:
elements = elements.OrderBy(frameworkElement => frameworkElement.Uid).ToList();

How to filter on the value of a specific element in a list?

Using GAE-Java-JDO, is it possible to filter on the value of a specific element in a list?
WHAT WORKS
Normally, I would have the following:
#PersistenceCapable
class A {
String field1;
String field2;
// id, getters and setters
}
Then I would build a simple query:
Query q = pm.newQuery(A.class, "field1 == val");
q.declareParameters("String val");
List<A> list = new ArrayList<A>((List<A>) q.execute("foo"));
WHAT I WOULD LIKE
The above works fine. But what I would like to have is all of the fields stored in a list:
#PersistenceCapable
class AA {
ArrayList<String> fields;
// id, getters and setters
}
and then be able to query on a specific field in the list:
int index = 0;
Query q = pm.newQuery(A.class, "fields.get(index) == val");
q.declareParameters("int index, String val");
List<A> list = new ArrayList<A>((List<A>) q.execute(index, "foo"));
But this throws an exception:
org.datanucleus.store.appengine.query.DatastoreQuery$UnsupportedDatastoreFeatureException:
Problem with query
<SELECT FROM xxx.AA WHERE fields.get(index) == val PARAMETERS int index, String val,>:
Unsupported method <get> while parsing expression:
InvokeExpression{[PrimaryExpression{strings}].get(ParameterExpression{ui})}
My impression from reading the GAE-JDO doc is that this is not possible:
"The property value must be supplied by the application; it cannot refer to or be calculated in terms of other properties"
So... any ideas?
Thanks in advance!
If you only need to filter by index+value, then I think prefixing the actual list-values with their index should work. (If you need to also filter by actual values, then you'll need to store both lists.)
i.e. instead of the equivalent of
fields= ['foo', 'bar', 'baz] with query-filter fields[1] == 'bar'
you'd have
fields= ['0-foo', '1-bar', '2-baz'] with query-filter fields == '1-bar'
(but in java)

Resources