Search code examples
asp.net-mvcmaster-pagesviewdata

How can I display a message in a master page with ViewData?


How can I display a message on the master page. The message is sent by the action.

public ActionResult DisplayMessage()
{
    ViewData["hello"] = "Hello!";
    return View();
}

Solution

  • In your view, do the following:

    <%= html.encode(ViewData("Hello")) %>
    

    If you want to place this data in another area outside of your view within your master page, you will need to define a new content placeholder.

    Master Page:

    <div id="somewhereOtherThanYourNormalViewArea">
        <asp:ContentPlaceHolder ID="SecondaryContent" runat="server" />
    </div>
    

    View:

    <asp:Content ID="Content2" ContentPlaceHolderID="SecondaryContent" runat="server">
        <%= html.encode(ViewData("Hello")) %>
    </asp:Content>