wf4
wf4

Reputation: 3827

How to declare a section of HTML/Razor to include in the same view

Is it possible in MVC Razor to define a section in a view to be used within that same view?

for example:

@section menu {
    @*Some code and markup here*@
}

//page continues here...

@RenderSection(menu)

This is the same code used to pull in scripts to the bottom of the _layout file but you can't use this when it's part of the same file.

Currently I have been using:

var menu = "@*Some code and markup here*@";

//page continues here...

@Html.Raw(menu)

But this is not ideal as there is no intellisense and can get quite messy once the contents grows.

Thanks in advance,

Will.

Upvotes: 1

Views: 331

Answers (1)

Romias
Romias

Reputation: 14133

In your case... you can use a Razor Helper, instead of a Section.

You define the piece of code you need to use/re-use in the same view one or several times:

@helper  MyMenu(int param1, string param2){
   //Your logic and markup here.
}

Then, at the bottom of your view you can use it:

@MyMenu(1, "foo")

Upvotes: 4

Related Questions