在ASP.NET MVC中使用的TempData - 最佳实践 [英] Using Tempdata in ASP.NET MVC - Best practice

查看:149
本文介绍了在ASP.NET MVC中使用的TempData - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC 3构建Web应用程序。

I am using ASP.NET MVC 3 to build a web application.

我所试图做的是两个控制器之间传递的价值观,虽然有很多方法可以做到这一点,我感到特别的兴趣使用的TempData 这一点。

What I am trying to do is pass values between two controllers, though there are many ways to do this I am particular interested in using TempData for this.

public ActionResult Action1()
{
    string someMessage;
    Test obj = SomeOperation();
    if(obj.Valid)
    {
        someMessage = obj.UserName;
    }
    else
    {
        someMessage = obj.ModeratorName;
    }

    TempData["message"] = someMessage;

    return RedirectToAction("Index");
}

public ActionResult Index()
{
    ViewBag.Message = TempData["message"]

    return View();
}

原来是使用的TempData 这里是否正确?我的意思是最好的下编程实践是使用这种正确的方法的TempData

So is the use of TempData here correct ? I mean under best programming practices is this correct way of using TempData ?

在什么实时病例应的TempData 使用吗?

In what real time cases should TempData be used ?

注意:我通过以下链接了

  • When to use TempData vs Session in ASP.Net MVC
  • http://www.gregshackles.com/2010/07/asp-net-mvc-do-you-know-where-your-tempdata-is/

感谢

推荐答案

的TempData 是一桶水,你可以转储只需要以下请求数据。也就是说,任何你投入的TempData是下一个请求完成后丢弃。这是一次性的消息,如表单验证错误非常有用。采取这里要注意的重要一点是,这适用于在会话的下一个请求,这样的请求可以在不同的浏览器窗口或标签可能发生。

TempData is a bucket where you can dump data that is only needed for the following request. That is, anything you put into TempData is discarded after the next request completes. This is useful for one-time messages, such as form validation errors. The important thing to take note of here is that this applies to the next request in the session, so that request can potentially happen in a different browser window or tab.

要回答您的具体问题:有使用它没有正确的方式。这一切都取决于易用性和便利性。如果一切正常,有意义,别人都理解它比较容易,这是很好的。在特定情况下,一个参数的传递这种方式是好的,但奇怪的是,你需要做的(code味道?)。我宁愿保持资源这样一个值(如果它是一个资源)或数据库(如果它是一个持久的价值)。从您的使用情况,这似乎是一种资源,因为你使用它的页面标题。

To answer your specific question: there's no right way to use it. It's all up to usability and convenience. If it works, makes sense and others are understanding it relatively easy, it's good. In your particular case, the passing of a parameter this way is fine, but it's strange that you need to do that (code smell?). I'd rather keep a value like this in resources (if it's a resource) or in the database (if it's a persistent value). From your usage, it seems like a resource, since you're using it for the page title.

希望这有助于。

这篇关于在ASP.NET MVC中使用的TempData - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆