neuquen
neuquen

Reputation: 4189

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 views:

@Html.Partial("PartialView")  

On a particular partial view, I have two DIVS:

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

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

However, I only want to include the content from divA. Can I do something like the following to only include the content from divA?

@Html.Partial("PartialView", @divA)  

If not, how can I do so?

Upvotes: 3

Views: 3133

Answers (2)

usefulBee
usefulBee

Reputation: 9702

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>
}

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

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") 

Upvotes: 5

Related Questions