ASP.NET MVC Razor Sections and Partials


April 2019


698 time


I'm relatively new to ASP.NET MVC and Razor. We've been modifying and developing based on existing code. Thus, there is a lot of duplication (ugh!). So I started looking at Partial pages and learning about Sections. I followed these tutorials but I'm still a bit confused.

ASP.NET MVC 3: Layouts and Sections with Razor

Various ways of using Shared Layout in ASP.NET MVC

Optional Razor Sections with Default Content

Razor, Nested Layouts and Redefined Sections

I've been able to create Sections with Partials in them. My question is:

While one section will always change upon user selection, I may not want to blow away the content section. I may just want to add a new tab based on the Sub Menu item selected by the user.

The plan is to have a _Layout that contains the _Header and a Section for the SideBar (Sub Menu). Based on the user's selection in the _Header, the Sub Menu list of options will change in the SideBar and the Content will be a container that can contain a Grid when the Home button is selected, or it can contain a Tabbed view for the other buttons.

enter image description here

The Problem

Let's say the user selects Billing from the _Header and then selects two items from the Sub Menu on the left; in the Content section, two tabs should display (one for each item selected in the Sub Menu). Then, if the user selects Reports from the _Header, the SideBar should changed to display the appropriate Sub Menu items for Reports but I do not want the two tabs for Billing to be blown away. Instead, I want to add additional tabs for each item the user selected from the Reports Sub Menu.

Below is the code from the demo, which shows how I put the Partial page code in the Sections. Obviously I'm still confused over the approach that I should take to accomplish the layout I need.


<!DOCTYPE html>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">


    <div id="header">
        <h1>My Site Header</h1>

    @if (IsSectionDefined("SideBar"))
        <div id="sidebar">

    <div id="content">

    <div id="footer">
        <p>Site Footer - &copy; Santa Clause</p>



    ViewBag.Title = "Home Page";


@section SideBar {




#header {
    background-color: #5c87b2;
    color: white;
    padding: 1px; }

#content {
    float: left;
    margin: 10px; }

#sidebar {
    float: left;
    margin: 10px;
    padding: 10px;
    border: dotted 5px red;
    width: 180px; }

#footer {
    text-align: center;
    clear: both; }


<p>This sidebar has "Home Page" specific content.</p>

    <li><a href="#">Link One</a></li>
    <li><a href="#">Link Two</a></li>
    <li><a href="#">Link Three</a></li>

<p>The time is: @DateTime.Now.ToShortTimeString()</p>


<h2>Welcome to my Site</h2>

<p>This is our home page.</p>

<p>Not super exciting is it?</p>

<p>Yada, Yada, Yada.</p>

0 answers