1

i am using a viewbag to show a drop down in view .. now when my post method is complete it returns back to view which then throws exception for dropdown because my view bag has nothing after that .

[HttpGet]
public ActionResult Add(string id)
{
    List<req> objlist = new List<req>();
    objlist = Getlist(Id);
    ViewBag.List = objlist;
    TempData["tempList"] = ViewBag.List;
    return View();
}

Above is my Get method and for POST method can i do this

[HttpPost]
public ActionResult Add()
{
    ViewBag.List =  TempData["tempList"];
    return View();
}

All this because i dont want Run the SQL Call again .

Haroon nasir
  • 648
  • 1
  • 7
  • 21
  • that's because `TempData["tempList"]` returns an `object` you need to typecast it to a specific type in your case `List` – Kunal Mukherjee Jan 11 '19 at 07:16
  • Why not just use `TempData["tempList"] = objlist` directly? Note that `TempData` stores data between redirects, if you want to pass data from view to controller by normal form submit try to use `HiddenFor` helper instead of `ViewBag` or `TempData`. – Tetsuya Yamamoto Jan 11 '19 at 07:17
  • Also worth to read these details about `ViewBag` and `TempData`: [ViewBag, ViewData, TempData, Session - how and when to use them?](https://stackoverflow.com/questions/15203870/viewbag-viewdata-tempdata-session-how-and-when-to-use-them) and [Difference Between ViewData and TempData?](https://stackoverflow.com/questions/173159/difference-between-viewdata-and-tempdata). – Tetsuya Yamamoto Jan 11 '19 at 07:21
  • @TetsuyaYamamoto i want this becasue i dont want to make round trip to sql for the same data again and again . – Haroon nasir Jan 11 '19 at 07:26
  • @KunalMukherjee But i dont think i can type cast my viewbag for tempdata . – Haroon nasir Jan 11 '19 at 07:27

2 Answers2

0

Modify your action methods to look like:


[HttpGet]
public ActionResult Add(string id)
{
    List<req> objlist = new List<req>();
    objlist = Getlist(Id);
    ViewBag.List = objlist;
    TempData["tempList"] = objlist;
    return View();
}

and

[HttpPost]
public ActionResult Add()
{
    ViewBag.List =  (TempData["tempList"] as List<req>) ?? new List<req>();
    return View();
}
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53
0

I'd recommend use model.

public class ModelClass
{
    public List<req> List { get; set; }
}

..

public void InitModel(string id, ModelClass Model)
{
    if(Model == null)
    {
        Model = new ModelClass();
    }

    Model.List = Getlist(id);
}

..

[HttpGet]
public ActionResult Add(string id)
{
    ModelClass Model = null;
    InitModel(id: id, Model: Model);
    return View(Model);
}

[HttpPost]
public ActionResult Add(ModelClass Model)
{
    InitModel(id: id, Model: Model);
    return View(Model);
}
Michael Samteladze
  • 1,310
  • 15
  • 38