Search code examples
c#asp.net-mvcroutestempdata

TempData gets overrided when I try to ReturnRedirect


I want to redirect to a previous page after I submit some data in database. I am using a TempData to retrieve ID on current Page, then I am going on the page with the form I want to submit (which have an ID), but after the POST method is fired TempData gets overrided by current page ID which is the page with the form and I want to ReturnRedirect to initial page with its ID.

Here the code:

Controller with GET method where I retrieve the ID:

var currentID = Url.RequestContext.RouteData.Values["id"];          
TempData["currentId"] = currentID;

Controller with POST method where I try to redirect:

if (ModelState.IsValid)
{
    // Editing records in database
    ....
    return RedirectToAction("Details", "Jobs", 
        new { controller = "JobsController", action = "Details", id = TempData["currentId"] });
}
ModelState.AddModelError("", "Something failed");
return View();

I am using this approach because its working if the current action with a POST method doesn't have an ID.

Thank you for any suggestions.

EDIT:

I have a Details of Jobs:

    // GET: Jobs/Details/5
    public ActionResult Details(Guid id)
    {
        var currentID = Url.RequestContext.RouteData.Values["id"];          
        TempData["currentId"] = currentID;

        var currentUserTemp = LoggedUserId;
        TempData["userID"] = currentUserTemp;

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Job job = db.Jobs.Find(id);
        if (job == null)
        {
            return HttpNotFound();
        }

        return View(job);
    }

But from this page I want a link to a page where I edit current user data.

View Details page Code:

@Html.ActionLink("Edit Company Details", "Edit", "UserAdmin", new { id = TempData["userID"] }, null)

Now I am on edit User Page, I edit the form and use save button (which triggers POST method) I want to use the other TempData variable to ReturnRedirect on Details Page but since both pages have ID`s, TempData gets overrided with last ID from the URL which is the ID of the user not ID.


Solution

  • Don't forget that TempData exists only during the time of a HTTP Request. Maybe it's a clue to your problem (I can't find all the interactions between Controllers and Views in your code so I can't be sure).