简体   繁体   English

我如何在MVC4中获得TempData对象识别

[英]How Can I Get TempData Object Recognize in MVC4

I have an ActionMethod that creates TempData object 我有一个可以创建TempData对象的ActionMethod

TempData["Message"] = new Message {Text = txtMessage, Success = false};

Then I read the TempData in the view like 然后我在视图中读取TempData

@{var message = TempData["Message"];}

But when I try to use the var "message.Success" the compiler doesn't recognize the property. 但是,当我尝试使用var“ message.Success”时,编译器无法识别该属性。 When I watch the var message and TempData during debug I can see the Object's txtMessage and Success value. 当我在调试过程中观看var消息和TempData时,我可以看到对象的txtMessage和Success值。 What am I missing? 我想念什么?

try 尝试

@{dynamic message = TempData["Message"];}

or 要么

@{Message message = TempData["Message"] as Message;}

or, if you know it will only ever be a Message 或者,如果您知道这只会是一条消息

@{Message message = (Message)TempData["Message"];}

I don't believe TempData is dynamically typed, so you need to cast it. 我不相信TempData是动态键入的,因此您需要进行TempData However, with an anonymous type, you cannot do that. 但是,对于匿名类型,您不能这样做。 You will need to convert your anonymous type to an actual class. 您将需要将您的匿名类型转换为实际的类。

If you don't want to do this, you might be able to use ViewBag instead, which is dynamically typed. 如果您不想这样做,则可以改为使用动态键入的ViewBag

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM