I can't see what's wrong with this code:
var listShoppingCart = Session["ShoppingCart"];
foreach (var item in listShoppingCart)
{
}
I get a red line below the listShoppingCart in the foreach loop. When I hover over the red line, the messages is that Foreach statement cannot operate on variables type 'object' because 'object' does not contain a public definition for 'GetEnumerator'
I declare the list with a session like this:
Session["ShoppingCart"] = new List<Products>();
You need to cast the session object
var listShoppingCart = Session["ShoppingCart"] as List<Products>;
if (listShoppingCart != null)
{
// Do stuff...
}
In the above code, we get the object located in the session at key "ShoppingCart" and cast that object to a List<Products>. If the cast cannot be done, then listShoppingCart will be null.
Because Session is of Type HttpSessionState and this implements ICollection.
Session values are stored in Dictionary<string,object> which implements ICollection. You need to type cast object to appropriate to enumerate over your list.
Related
Is there a way to check if your session variable contains something... Just like a list has a method "Contains". Is there something similar to that? Some method or something?
Hi you can try casting your session so it can have a type for example
var listofperson = Session["ListofPerson"] as List<string>;
var hasGeorge = listofperson.Contains("George");
When you retrieve items from Session, they are of type System.Object. This means that you don't get any of the actual methods available for the object's real type. You can do so by casting it to the correct type. In this case, it sounds like you're storing a List<string>. So we can use the as operator. If the object is not of that type or was null to begin with, myList will null. Otherwise it will be of the type you specify.
List<string> myList = Session["myKey"] as List<string>();
if(myList == null)
{
//either Session["myKey"] was null or the object wasn't a List<string>
}
else
{
if(myList.Contains("fuzzy puppies"))
{
//your list contains fuzzy puppies
}
else
{
//your list doesn't contain fuzzy puppies
}
}
Calling .ToString() on an object gives you different results based on the object type. The default behavior is to print out the type of the object. But types can override this behavior. For example, calling .ToString() on a string just gives you the string itself. Calling .ToString() on an object that represents some XML might give you the XML as a string. Since List<string> doesn't override the default behavior of System.Object.ToString(), it just prints out "System.Collections.Generic.List`1[System.String]"
First, check if Session["yoursession_var"] is null. Then cast to List(). Then use Exists(), as described here: how to use Exist in List<string> in C#
i am getting error "Object reference not set to an instance of an object." my is here,
public class UserProfession
{
public UserProfession()
{
}
public System.String[] Designation
{
get;
set;
}
}
then i am using it like,
UserProfession.Designation[0] =txt_Search.Text.ToString();
Error i mentioned you hopes for your suggestions .
-Thanks
When you make an assignment to an array property, like this:
UserProfession.Designation[0] =txt_Search.Text.ToString();
what you are actually doing is calling the get section for that property... not the set. This returns the object supported the property... the whole object, and not just the index. Index lookup does not happen until after the object is returned. Once you have that object, accessing an index works in the normal way.
You get this specific exception because you have the expression UserProfession.Designation that should return a reference to an array object, but because you never initialize the array there is nothing there when you then try to find reference the 0th element. At this point the framework discovers that the array (your "object reference") is "not set to an instance of an object"... which is just a fancy way of saying it's null.
In other words, you need to have an already existing array to hold the value you want to assign. That means doing something like this:
Designation = new String[10];
public String[] Designation
{
get;
set;
}
However, notice that we never used the set section? So you can simplify that further, like this:
Designation = new String[10];
public String[] Designation {get;private set;}
This will keep client code from completely swapping an entire array out from under your object, but otherwise will provide the full functionality of an array property. If you provide your own backing store for the array, you could even get rid of the setter entirely with no loss of functionality:
private string[] _designation = new string[10];
public string[] Designation {get {return _designation;} }
But let's add one more wrinkle: your desire to assign the to array before initializing it indicates to me that you likely don't really know how big it will be up front. If that's the case, you probably want a collection of some kind instead of an array. A generic List is a convenient and very compatible replacement for an array. That would look like this:
private List<string> _designation = new List<string>();
public List<string> Designation {get {return _designation;}}
You can still access items in that list by index, just like you would with an array. The only difference you need to worry about right now is how you add new items:
UserProfession.Designation.Add(txt_Search.Text);
Also notice that I removed the .ToString() call. Since your .Text property is almost certainly already a string, calling the .ToString() method is just silly.
You will have to initialize the object, before assigning the value. The initialization should be done just once. I have initialized the array size to ten. You can have your own values here. If you want to resize dynamically, you can use ArrayList
int length = 10;
UserProfession.Designation = new System.String[length];
UserProfession.Designation[0] =txt_Search.Text.ToString();
For more information: http://msdn.microsoft.com/en-us/library/aa287601(v=vs.71).aspx
it must initialize the value before we use because, currently, it is null.
you better add the initialization code in the constructor function.
Hello I'd like to ask if you can assign arrays of beans as a form
for example i have a form:
PageForm{
Group[] groupArray;
Group[] getGroupArray(){
return groupArray;
}
void setGroupArray( Group[] groupArray ){
this.groupArray = groupArray;
}
}
Group{
boolean isChecked;
boolean getIsChecked(){
return isChecked;
}
void setIsChecked( boolean ischecked ){
this.isChecked = ischecked;
}
}
id like to access this group array in my jsp.
can i do that using this:
<spring:form>
<spring:checkbox path="groupArray[0].isChecked" />
<spring:checkbox path="groupArray[1].isChecked" />
<spring:checkbox path="groupArray[2].isChecked" />
</spring:form>
What i get is an exception:
org.springframework.beans.NullValueInNestedPathException:
Invalid property 'groupArray[0]' of
bean class [PageForm]: Cannot access
indexed value of property referenced
in indexed property path
'groupArray[0]': returned null
Please help me.
Thanks.
The problem is that Group[] groupArray has not been initialized, so when it goes to the array and looks for the object Group at position 0 it cannot find the Group object.
If you know in advance the number of objects which there can be in the array you can insert as many Group objects as you need in the array groupArray in the constructor of PageForm.
In case you don't know how many object you'll have in the array (because you'll create them from data coming from a form) you'll need to provide a way to create new Group objects when the object has not been instantiated in that position before. I think the easiest way toget this is to change your Group[] array to a List<Group> and use a lazy list like Spring AutoPopulatingList, Apache Commons Collections LazyList or the one provided by the library Guava.
try to change your attribute name maybe myChecked and getter/setter as well
e.g. getChecked and setChecked
Is it possible to pass a parameter to a method ByRef (or out etc) in ActionScript 3?
I have some globally scoped variables at the top of my class and my method will populate that variable if it's == null.
I'm passing in the variable which needs to be populated but so far my efforts have returned a locally populated variable leaving the globally scoped version of it still null.
The variable being passed to my method varies so I can't hardcode it in my method and simply set it.
ActionScript 3 passes params by reference by default, like Java - except for primitive types. But what you are trying to have it do isn't passing by reference. The parameter passed in is a reference to an object(in the case when it's not a primitive type), which you may well modify inside of the function.
But, to answer your question. Here is a solution:
function populateIfNull(variableName, value){
this[variableName] = this[variableName] || value
}
Which you can use like:
populateIfNull('name', 'Bob')
populateIfNull('age', 20)
AS3 does not have pass by reference (it is similar to Java in this regard, in that it passes references by value).
Something similar can be simulated if you control the client code by wrapping the object in another object:
var myObj = null;
myFun({ a: myObj });
function (param) {
if (param.a == null) {
param.a = "Hello";
}
}
Use objects.
eg:
var myObj : Object = new Object();
var myArr : Array;
myObj.arr = myArr;
function populateViaRef(obj : Object) : void {
obj.arr = new Array();
for(var i : Number = 0; i < 10; i++)
obj.arr[i] = i;
}
populateViaRef(myObj);
for(var i : Number = 0; i < 10; i++)
trace(myObj.arr[i]);
In ActionScript 3.0, all arguments are passed by reference, because all values are stored as objects. However, objects that belong to the primitive data types, which includes Boolean, Number, int, uint, and String, have special operators that make them behave as if they were passed by value.
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f56.html
In Java arguments are passed by value.
http://javadude.com/articles/passbyvalue.htm
im having trouble with the result of a webservice call. When the result comes in and kicks off the resultHandler function i set a break point so i can examine the result. I can see that there are 0 records in the array collection however i can see content so im assuming that the zero is just referring to the first index of the array
the problem happens when i try assign the value to an array collection as follows;
public function resultHandler(event:ResultEvent):void{
var result:ArrayCollection = event.result as ArrayCollection;
the result of this operation is a result var with the value of null. Can anyone explain what could be happening here? thanks a lot
another thing i just noticed is that the result type is mx.utils.ObjectProxy, im expecting an array
If the webservice returns just one element, it will be deserialized as ObjectProxy. You will have to manually convert it into an array.
I'd normally do this after a WS call:
if (event.result is ArrayCollection) {
result = event.result;
}
else {
result = new ArrayCollection([event.result]);
}
Chetan is right -- the cast operation to ArrayCollection is failing, because the source object is not an ArrayCollection. Try this instead:
public function resultHandler(event:ResultEvent):void
{
var ac:ArrayCollection = new ArrayCollection([event.result])
// ...
}
The "as" operator will return null in situations where an exception would occur at runtime -- in your case, casting from ObjectProxy to ArrayCollection. If instead you pass event.result as the sole member of an array (by surrounding it with []), your ArrayCollection will be constructed properly, and you'll be able to retrieve the object normally:
var o:Object = ac.getItemAt(0) as Object;
trace(o.yourObjectProperty.toString());
Hope it helps!
0 records in the array is the length of the array, that actually means 0. If you have something in index 0 of an array, that array has a length of at least 1. It looks like you aren't getting any data back, not even and empty array collection.
The problem in my opinion is that you cannot cast event.result as an array collection, but you have to cast it as an array.
The best practice in this is having a getter and a setter:
private var _acLocation:ArrayCollection=new ArrayCollection;
public function set acLocation(acLocation:ArrayCollection):void{
_acLocation=acLocation;
//do this if you want for exaple to assign the arraycollection to a datagrid dataprovider
dgMyDataGrid.dataProvider=_acLocation;
}
public function get acLocation():ArrayCollection{
return _acLocation;
}
Then in the result handler function of a service call, code
acLocation=new ArrayCollection(event.result as Array);
Hope it helps