kumar
kumar

Reputation: 9387

MVC ViewBag for partial view is null

Have a basic question regarding partial view.the @ViewBag.Message comes out empty in the final render.

My controller looks like this

    public ActionResult Message() {
        ViewBag.Message = "This is a partial view.";
        return PartialView();
    }

    public ActionResult PartialViewDemo() {
        return View();
    }

My partial view looks like this in Message.cshtml

<h2>@ViewBag.Message</h2>

I am calling the partial view like this from partialViewTest.cshtml. the @ViewBag.Message is empty and only h2 tag is shown.

<div>@Html.Partial("~/Views/Sample/Message.cshtml")</div>

If i implement using javascript it works fine

<div id="result"></div>

@section scripts {
    <script type="text/javascript">
        $(function () {
            $('#result').load('/sample/message');
        });
    </script>
}

Upvotes: 0

Views: 1607

Answers (1)

Mahedi Sabuj
Mahedi Sabuj

Reputation: 2944

You Render Message.cshtml only (not controller) from partialViewTest.cshtml. As you set ViewBag.Message in the controller, you have to call the controller (to get partial view) like this.

@Html.Action("Message", "Sample")

Upvotes: 2

Related Questions