Partial Views and what happens when we forget to write Layout = null?

First you can read an article about Partial views: URL

They allow you to move out the repeating content in your website like footer and header in a separate place. That place is the Action method of the Controller.
Except that you can send data in form of a model to the partial view, so you don’t have to repeat yourself in every controller.
So using that case I have a Common controller with methdod NavBar and in this method I’m returning as a result view, which represents the navigation bar at the header, which is always shown in the website.
Here is the method:

public ActionResult NavBar()
var currentUser = accountService.CurrentUser;
var model = new NavBarViewModel
Email = currentUser.Email,
FirstName = currentUser.FirstName,
LastName = currentUser.LastName

return View(model);

So I am taking the currently logged in user name and displaying it in the navigation bar. I’m using the ChildActionOnly attribute which does not allow a method to be called in example as in a GET query.
Here is the code for the View

@model Web.Models.Common.NavBarViewModel
Layout = null;
ViewBag.Title = "NavBar";


And this is how it is used:

@Html.Action("NavBar", "Common")

This Partial View can be placed wherever you want in your HTML code so you don’t have to repeat yourself at many places. And the problem I faced was that I forgot to write that the Layout = null for the partial view. So after that one messy execution of the javascript began due to the not proper rendering of the navigation bar. Please keep that in mind!

You may also like...