Anthony Don
Anthony Don

Reputation: 157

How Can I Get TempData Object Recognize in MVC4

I have an ActionMethod that creates TempData object

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

Then I read the TempData in the view like

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

But when I try to use the var "message.Success" the compiler doesn't recognize the property. When I watch the var message and TempData during debug I can see the Object's txtMessage and Success value. What am I missing?

Upvotes: 3

Views: 2106

Answers (2)

cwharris
cwharris

Reputation: 18125

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"];}

Upvotes: 4

cadrell0
cadrell0

Reputation: 17307

I don't believe TempData is dynamically typed, so you need to cast it. 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.

Upvotes: 1

Related Questions