I have certain situations where I need to pass a value between controller actions.
When passing a returnUrl from a view to all nested views. In the view I have
@{ TempData["returnURL"] = Request.Url.AbsoluteUri; }and then access it in a similar way to this (in my real version I check that the key is in TempData and that the returnURL is a real URL):
return Redirect(TempData["returnURL"].ToString());If it needs to continue on past the first page change (i.e. Search page -> Edit page -> Edit Section page) I'm adding it again
TempData["returnURL"] = TempData["returnURL"];When I need to pass a value from one controller action through a view to another controller action that is called by ajax such as here:
public ViewResult Index(FormCollection form) { var model = new GridColumnChooserViewModel(); //Select deleted/not deleted rows if (form.HasKeys()) model.ShowRows = (form["deletedDropDown"] == null) ? "Active" : GetOptionByName(form["deletedDropDown"]); TempData["ShowRows"] = model.ShowRows; ... }and then in my other ajax-called action controller I access it:
public JsonResult GetData() { //Select deleted/not deleted rows var showRows = (TempData.ContainsKey("ShowRows") && TempData["ShowRows"] == null) ? "Active" : GetOptionByName(TempData["ShowRows"].ToString()); //refresh tempdata showrows so it is there for next call TempData["ShowRows"] = model.ShowRows; return this.GetDataSource(showRows); }
My question is, is this really bad practice? From my understanding of it, I'm essentially using TempData like a session cookie. Is there a better way to do this, like using an actual cookie?
FormCollectionis deprecated. - Daniel A. White