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.
When you do this
the content of
~/Views/Shared/Messages.ascx
will be rendered, but the controller action method below won't be executedso
ViewBag.MyMessage
is null and you got the error because of this syntaxYou need to execute the controller action method using
Html.Action
method in your view. Since the controller class isMessagesController
, change this syntaxto this