((List<string>)Session["answera"]).Add(xle.InnerText);
I need to perform this operation, but I get "Object reference not set to an instance of...." I don't want to use
List<string> ast = new List<string>();
ast.Add("asdas!");
Session["stringList"] = ast;
List<string> bst = (List<string>)Session["stringList"];
as I merely want to add a string to the Session-String-Array.
Have you thought about wrapping your List<string>
in a property of a custom context object? I had to do something like that on an application, so I ended up creating what was for me a UserContext
object, which had a Current
property, which took care of creating new objects and storing them in the session. Here's the basic code, adjusted to have your list:
public class UserContext
{
private UserContext()
{
}
public static UserContext Current
{
get
{
if (HttpContext.Current.Session["UserContext"] == null)
{
var uc = new UserContext
{
StringList = new List<string>()
};
HttpContext.Current.Session["UserContext"] = uc;
}
return (UserContext) HttpContext.Current.Session["UserContext"];
}
}
public List<string> StringList { get; set; }
}
I actually got most of this code and structure from this SO question.
Because this class is part of my Web
namespace, I access it much as I would access the HttpContext.Current
object, so I never have to cast anything explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With