How do I add a partial view with its own controller to another view in asp.net mvc 4

627 Views Asked by At

I have a partial view with just a single line called Messages.ascx which is in the location ~/Views/Shared/Messages.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<h2><%:ViewBag.MyMessage.ToString() %></h2>

The controller of the partial view is as follows

public ActionResult Messages()
{
    ViewBag.MyMessage = "This is my Partial Message";
    return PartialView();
}

I just need the to add this partial view in my index.asp page which is located in ~/Views/Home/Index.aspx. I added the partial view as follows

<%: Html.Partial("Messages") %>

However when I compile and run I get the following message on my browser

Cannot perform runtime binding on a null reference

Line 1:  <%@ Control Language="C#"> Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %> 
Line 2:
Line 3:  <h2><%:ViewBag.MyMessage.ToString() %></h2>

Kindly help me as to how do I add the partial view to my main view.

1

There are 1 best solutions below

0
On BEST ANSWER

When you do this

<%: Html.Partial("Messages") %>

the content of ~/Views/Shared/Messages.ascx will be rendered, but the controller action method below won't be executed

public ActionResult Messages()
{
    ViewBag.MyMessage = "This is my Partial Message";
    return PartialView();
}

so ViewBag.MyMessage is null and you got the error because of this syntax

<h2><%:ViewBag.MyMessage.ToString() %></h2>

You need to execute the controller action method using Html.Action method in your view. Since the controller class is MessagesController, change this syntax

<%: Html.Partial("Messages") %>

to this

<%: Html.Action("Messages", "Messages") %>