我有一些情况需要在控制器操作之间传递一个值。
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); }
我的问题是,这样做真的是不好的实践吗?据我理解,我基本上是像使用会话cookie一样使用TempData。有没有更好的方法来做到这一点,比如使用实际的cookie?
FormCollection
已被弃用。 - Daniel A. White