Search code examples
asp.net-mvc-2tempdata

TempData moving from view to controler


I am attempting to call a controller via an actionLink() in a view. This controller get's data from a TempData repository. However, it seems that no matter what I do, if I set the TempData repository in the view, it won't go over to the controller? Should I use ViewData instead? What is your recommendation for a system such as that?

Thanks


Solution

  • TempData, nor ViewData is supposed to be set in a view. A view is supposed to consume data that has been stored in those structures inside your controller actions (well, actually it isn't, a view is supposed to consume a view model but that's another topic).

    TempData could be used when you want to persist information between two redirects. It should be set inside a controller action which redirects to another controller action that will read the data:

    public ActionResult Foo()
    {
        SomeModel model = ...
        TempData["foo"] = model;
        return RedirectToAction("Bar");
    }
    
    public ActionResult Bar()
    {
        var model = TempData["foo"] as SomeModel;
        ...
    }
    

    So a controller action should get data from the TempData structure only if this action has been invoked after a redirect from another action that set the data. Such controller action should never be invoked from a view because if you have a view this means that this view was rendered from a controller action that presumably set the data into TempData but there is always a risk (if the view performs in between a request to the server - AJAX or something), the TempData will be lost.

    For your case, when a view needs to invoke the server there are basically 3 techniques:

    • Use an HTML <form> with input fields that will send the data to the server
    • Use an anchor and pass data as query string parameters to the controller
    • Use javascript and send an AJAX request or a redirect to the server