Skip to content Skip to sidebar Skip to footer

Include Only Part Of A Partial View With ASP.NET Razor MVC

I am using ASP.NET Razor MVC and am using Partial Views for common content that I don't want to update on every single page. I am using the below syntax to include my partial vie

Solution 1:

You could make the partial strongly typed to a view model:

public class MyViewModel
{
    public bool ShowOnlyPartA { get; set; }
}

and then make your view strongly typed to this model:

@model MyViewModel

<div class="divA">
    CONTENT
</div>

@if (Model == null || !Model.ShowOnlyPartA)
{
    <div class="divB">
        CONTENT
    </div>
}

and then you could call your partial like this:

@Html.Partial("PartialView", new MyViewModel { ShowOnlyPartA = true }) 

or like this:

@Html.Partial("PartialView") 

Solution 2:

Excellent question as well as an answer from Darin. As an alternative, pass a string instead:

<!-- View -->
@Html.Partial("PartialView", "divA") 

<!-- PartialView -->
@if (Model == "divA")
{
  <div class="divA">
  </div>
}

@if (Model == "divB")
{
  <div class="divB">
  </div>
}

Post a Comment for "Include Only Part Of A Partial View With ASP.NET Razor MVC"