Asp.net MVC User Control ViewData
Asked Answered
D

2

7

When a controller renders a view based on a model you can get the properties from the ViewData collection using the indexer (ie. ViewData["Property"]). However, I have a shared user control that I tried to call using the following:

return View("Message", new { DisplayMessage = "This is a test" });

and on my Message control I had this:

<%= ViewData["DisplayMessage"] %>

I would think this would render the DisplayMessage correctly, however, null is being returned. After a heavy dose of tinkering around, I finally created a "MessageData" class in order to strongly type my user control:

public class MessageControl : ViewUserControl<MessageData>

and now this call works:

return View("Message", new MessageData() { DisplayMessage = "This is a test" });

and can be displayed like this:

<%= ViewData.Model.DisplayMessage %>

Why wouldn't the DisplayMessage property be added to the ViewData (ie. ViewData["DisplayMessage"]) collection without strong typing the user control? Is this by design? Wouldn't it make sense that ViewData would contain a key for "DisplayMessage"?

Decile answered 20/8, 2008 at 20:46 Comment(0)
P
6

The method

ViewData.Eval("DisplayMessage") 

should work for you.

Paediatrics answered 28/8, 2008 at 6:41 Comment(0)
D
2

Of course after I create this question I immediately find the answer after a few more searches on Google

http://forums.asp.net/t/1197059.aspx

Apparently this happens because of the wrapper class. Even so, it seems like any property passed should get added to the ViewData collection by default.

I really need to stop answering my own questions :(

Decile answered 20/8, 2008 at 21:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.