TempData 从视图移动到控制器
我试图通过视图中的 actionLink()
调用控制器。该控制器从 TempData 存储库获取数据。但是,似乎无论我做什么,如果我在视图中设置 TempData 存储库,它都不会转到控制器吗?我应该使用 ViewData
来代替吗?您对这样的系统有何建议?
谢谢
I am attempting to call a controller via an actionLink()
in a view. This controller get's data from a TempData repository. However, it seems that no matter what I do, if I set the TempData
repository in the view, it won't go over to the controller? Should I use ViewData
instead? What is your recommendation for a system such as that?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
TempData 和 ViewData 都不应该在视图中设置。视图应该使用存储在控制器操作内的那些结构中的数据(实际上不是,视图应该使用视图模型,但这是另一个主题)。
当您想要在两个重定向之间保留信息时,可以使用 TempData。它应该在重定向到另一个将读取数据的控制器操作的控制器操作内设置:
因此,仅当在从设置数据的另一个操作重定向后调用此操作时,控制器操作才应从 TempData 结构获取数据。这样的控制器操作永远不应该从视图中调用,因为如果您有一个视图,这意味着该视图是从控制器操作渲染的,该控制器操作可能将数据设置到 TempData 中,但总是存在风险(如果视图在请求之间执行)服务器 - AJAX 或其他),TempData 将丢失。
对于您的情况,当视图需要调用服务器时,基本上有 3 种技术:
TempData, nor ViewData is supposed to be set in a view. A view is supposed to consume data that has been stored in those structures inside your controller actions (well, actually it isn't, a view is supposed to consume a view model but that's another topic).
TempData could be used when you want to persist information between two redirects. It should be set inside a controller action which redirects to another controller action that will read the data:
So a controller action should get data from the TempData structure only if this action has been invoked after a redirect from another action that set the data. Such controller action should never be invoked from a view because if you have a view this means that this view was rendered from a controller action that presumably set the data into TempData but there is always a risk (if the view performs in between a request to the server - AJAX or something), the TempData will be lost.
For your case, when a view needs to invoke the server there are basically 3 techniques:
<form>
with input fields that will send the data to the server您应该预先在呈现视图的控制器中设置 TempData 值。然后,渲染第二个 (ActionLink) 视图的控制器操作将获取该值。
You should set the
TempData
value beforehand, in the controller that renders your view. The value will then get picked up by the controller action that renders your second (ActionLink) view.