user911275
user911275

Reputation:

Need to retrive values from Session object using foreach in mvc3?

I have mvc 3 application in which in session object i'm taking all values that is needed to me as parameter to execute stored procedure.

If the userAction is update then execute stored procedure.

public ActionResult Index(string userAction) 
{ 
   if(Session["Mappings"] != null)            
        ViewData["Message"] = "Mapping web grid"; 

    if (Session["PricingSecurities"] == null) 
        Session["PricingSecurities"] = objRepository.GetPricingSecurityID(); 
    if (Session["Cusips"] == null) 
        Session["Cusips"] = objRepository.GetCUSIP(); 

    SecurityMappingModel objModel = null; 
    mappings = (List<SecurityMappingModel>)Session["Mappings"]; 

    objModel = new SecurityMappingModel(); 


    if (userAction == "Update" ) 
    { 
        //help me to fix this code 

        //foreach (var item in Session)
        //{Session["Mappings"] //NEED FIX HERE
        //}
        // PLEASE HELP ME TO RETRIEVE SESSION VALUES
        return RedirectToAction("Index"); 
    } 
    return View(objModel); 
} 

HOW CAN I RETRIEVE ALL VALUES OF Session["Mappings"] it is holding 3entries 3ids,3cusips,3calculation

Upvotes: 0

Views: 643

Answers (1)

mgnoonan
mgnoonan

Reputation: 7200

The short answer is to not use var as your enumeration type, use object instead.

foreach (obj item in Session) {
    if (item is CUSIP) {
        // CUSIP processing
    } else if (item is PricingSecurity) {
        //Pricing security processing
    } //etc.
}

As you can see, the problem with this approach is that you will have to test each object for it's type in order to perform any custom action on it. A better idea would be to create your own class to store in the session:

public class SessionData()
{
    List<CUSIP> Cusips {get;set;}
    List<PricingSecurity> PricingSecurities {get;set;}

    public SessionData()
    {
        // Initialize the lists so they are never null
        this.Cusips = new List<CUSIP>();
        this.PricingSecurities = new List<PricingSecurity>();
    }
}

Then you can just loop through each of the list properties and perform any actions you need.

Upvotes: 1

Related Questions