Reputation: 7626
I have assigned session a custom class's object like:
Services Obj = getServiceDetails(3); //getting all data of Service where Id = 3
Session["ServiceObj"] = Obj;
Now I want to assign its value to same class's another object in a model class. I don't know how to do it.
I tried but it is not valid way.:
Services oldObj = <Services>Session["ServiceObj"];
Pls Help me. I don't know how to do it.
Upvotes: 6
Views: 12285
Reputation: 181
to get value from session you should cast it.
Services oldObj = (Service)Session["ServiceObj"];
Upvotes: 0
Reputation: 107247
You can also refactor the typed data retrieval using a generic, e.g. using an extension method, like so:
public static class MyExtensions
{
public static T GetTypedVal<T>(this HttpSessionState session, string key)
{
var value = session[key];
if (value != null)
{
if (value is T)
{
return (T)value;
}
}
throw new InvalidOperationException(
string.Format("Key {0} is not found in SessionState", key));
}
}
Which you can then use for reference and value types, like so:
Session["Value"] = 5;
var valResult = Session.GetTypedVal<int>("Value");
Session["Object"] = new SomeClass() { Name = "SomeName" };
var objResult = Session.GetTypedVal<SomeClass>("Object");
Upvotes: 1
Reputation: 845
Cast it with your Class like this
Services obj = (Services)Session["ServiceObj"];
Upvotes: 1
Reputation: 15893
Correct type cast requires round brackets:
Services oldObj = (Services)Session["ServiceObj"];
Upvotes: 10
Reputation: 1728
you should use Services oldObj = (Services)Session["ServiceObj"];
instead of Services oldObj = <Services>Session["ServiceObj"];
Upvotes: 2