在控制器之间传递详细信息,使用TempData是一种不好的做法吗?

4

我有一些情况需要在控制器操作之间传递一个值。

  1. 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"];
    
  2. 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?


FYI - FormCollection已被弃用。 - Daniel A. White
还有,视图设置任何内容都是一个不好的主意。 - Daniel A. White
1
在哪里说FormCollection已被弃用?MSDN上没有提到:http://msdn.microsoft.com/en-us/library/system.web.mvc.formcollection.aspx。 - dnatoli
最好的做法是使用强类型模型。 - Daniel A. White
3个回答

1

看起来你正在使用TempData在网站的各个页面之间流动状态;总的来说,我认为这是一种不好的做法。

理想情况下,你应该将任何即将需要的状态流向客户端,并且客户端会将其存储(以某种JSON或其他方式)。然后,客户端将其作为其操作的一部分返回给你,然后你会传回适当的状态等等;这更符合HTTP应用程序无状态的特性。


1

是的,我认为这通常是不好的做法。虽然ViewData字典方法快速且相当容易实现,但它可能会导致在编译时未被捕获的错别字和错误。另一种选择是使用ViewModel模式,它允许您为需要公开值或内容的特定视图使用强类型类。最终为您提供类型安全和编译时检查以及智能感知。

我的首选是使用视图模型。如果不适合,则使用会话状态可能就可以了。


0

我将两种情况都改为使用Session,这样我就不必一直推送TempData值了。

public ActionResult Create()
{
    Session["returnURL"] = Request.UrlReferrer.AbsoluteUri;
    ...
}

然后我像这样访问它

var returnURL = (Session["returnURL"] != null) ? Session["returnURL"].ToString() 
                                               : Url.Action("Index", "Home");

看起来好了一点。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接