Include only part of a partial view with ASP.NET Razor MVC

非 Y 不嫁゛ 提交于 2019-12-10 18:06:47

问题


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?


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



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


来源:https://stackoverflow.com/questions/19386067/include-only-part-of-a-partial-view-with-asp-net-razor-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!