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

查看:22
本文介绍了在 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 ?

注意:我已经浏览了以下链接

谢谢

推荐答案

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.

回答您的具体问题:没有正确的使用方法.这完全取决于可用性和便利性.如果它有效,有意义并且其他人相对容易理解它,那就太好了.在您的特定情况下,以这种方式传递参数很好,但是您需要这样做很奇怪(代码异味?).我宁愿在资源(如果是资源)或数据库(如果是持久值)中保留这样的值.从您的使用情况来看,它似乎是一种资源,因为您将其用于页面标题.

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天全站免登陆