ASP.NET MVC USER CONTROL VIEWDATA

marcel ethan

Total Post:105

Points:735
Posted by  marcel ethan
 1731  View(s)
Ratings:
Rate this:

Hi Everyone!

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

Thanks in advance

  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Asp.net MVC User Control ViewData

    Hi Marcel Ethan!

    For display message, you can Eval Method as below

    ViewData.Eval("Put your message here")

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!