Search code examples
asp.net-mvcmodeltempdata

Keeping data between ActionResults


I am populating a list based on data returned from a stored procedure, this first occurs in the SpecificArea ActionResult:

public ActionResult SpecificArea(ModelCallDetails call, int id = 0 )
    {

        ReturnSpecificAreas(call, id);
        return PartialView("SpecificArea", listCallDetails);
    }

When the list is displayed each row is an actionlink, which will sends the data to the SpecificAreaWorker:

[HttpGet]
    public ActionResult SpecificAreaWorker(ModelCallDetails call, int id)
    {           
        TempData["StringOfIds"] = StringOfIds;
        ReturnSpecificAreas(call, id);
        if (ResponseMessage == "Successful")
        {



            return PartialView("SpecificArea", listCallDetails);
        }

        else
        {

            return RedirectToAction("ViewCall");


        }

    }

I am wanting to collect the id of each row that is clicked and store them in a list in the model so that I can create a string of id's. However, each time a row in the table is clicked it refreshes the model, and I no longer have a list of ids anymore.

  public void ReturnSpecificAreas(ModelCallDetails call, int id)

    {

        SelectedAffectedServiceID = id;
       call.AffectedServiceList.Add(SelectedAffectedServiceID);

        foreach (int item in call.AffectedServiceList)
        {
            if (TempData["StringOfIds"] != null)
            {
                StringOfIds = TempData["StringOfIds"].ToString();
                StringOfIds += string.Join(",", call.AffectedServiceList.ToArray());

            }

            else
            {

                StringOfIds += string.Join(",", call.AffectedServiceList.ToArray());
            }

        }

I have tried to mantain the data in tempdata, but can't manage to execute this -will the tempdata refresh each time the actionlink is clicked? Is there a better way to achieve this?


Solution

  • I believe you are using MVC5? If so, use

    System.Web.HttpContext

    This gets current request

    to save....

    System.Web.HttpContext.Current.Application["StringOfIds"] =  StringOfIds;  //Saves global
    System.Web.HttpContext.Current.Session["StringOfIds"] =  StringOfIds;  //Saves Session
    

    To retrieve...

    StringOfIds = (string) System.Web.HttpContext.Current.Application ["StringOfIds"]; //Retrieves from global memory
    StringOfIds = (string) System.Web.HttpContext.Current.Session ["StringOfIds"]; //retrieves from session memory
    

    Good luck.