Asp.net MVC User Control ViewData

Question :

Asp.net MVC User Control ViewData,

Answer :

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  

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”?

,

The method

ViewData.Eval("DisplayMessage")   

should work for you.

That’s the answer Asp.net MVC User Control ViewData, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you

Read More  How to capture output of “pnputil.exe -e”