Mvc3 embed partial view in another

I have a partial view, which consists of a div with benner, which I change once a week. This banner is embedded in 10 pages having the same layout.

Give a page like Index.cshtml or AboutUs.cshtml, both are partial views and have laypout _Layout.cshtml my question is:

Can I enter the code in Index.cshtml or AboutUs.cshtml that displays Banner.cshtml?

sort of:

inside Index.cshtml or AboutUs.cshtml I have @ Html.Renderbanner ("banner.cshtml");

+6
source share
5 answers

Yes,

@{ Html.RenderPartial("_Banner"); } 

In your shared view folder, add a partial view and name it _Banner.cshtml

+6
source

Of course, you can always:

 @Html.Partial("Banner") 

from any kind or partial representation. This will lead to a partial part of Banner.cshtml in the place where you called this helper.

+1
source

Use @ Html.RenderPartial ("YourViewName");

+1
source

First, just to clarify: Are Index and AboutUs partial representations in your script? This may change my advice, but usually I see three options:

  • Razor helper , create Banner.cshtml in App_Code with the following code:

     @helper Show(){ <img src="mybanner.png"/> } 

    Then call in Index.cshtml:

     @Banner.Show() 
  • The Html Helper Extension may be a bit overkill here (see web UI guide)

  • Partial view : create "_MyBanner.cshtml" and use the following in Index.cshtml:

     @Html.Partial("_MyBanner"); 

(Number 3 is one that can be complicated if Index and AboutUs are also partial views, but 1 is the one I would choose.)

Note. There is a difference between Html.Partial and Html.RenderPartial. The latter writes directly to the output stream and requires that you call it in parentheses. In MVC AFAIK, it is recommended to use Html.Partial.

0
source

You can create a RenderSection in layout.cshtml

  @if (IsSectionDefined("Sidebar")) { <div id="page"> <!-- end #content --> <div id="content"> @RenderBody() </div> <div id="sidebar"> @RenderSection("Sidebar", required: false) </div> <div style="clear: both;"> &nbsp;</div> </div> <!-- end #page --> <!-- end #sidebar --> } else { <div id="page"> <!-- end #content --> <div id="content2"> @RenderBody() </div> <div style="clear: both;"> &nbsp;</div> </div> <!-- end #page --> <!-- end #sidebar --> } 

if you need to see the section in about.cshtml

use

 @section Sidebar{ @Html.Partial("_yourbanner") } 

If you do not need a banner, do not turn it on

0
source

Source: https://habr.com/ru/post/899300/


All Articles