2

I have a file called TopBar.cshtml:

<nav class="white" role="navigation">
    <div class="nav-wrapper container">
        <a id="logo-container" href="#" class="brand-logo">Logo</a>
        <ul class="left hide-on-med-and-down">
            <li><a href="#">Navbar Link</a></li>
        </ul>
        <ul id="nav-mobile" class="sidenav">
            <li><a href="#">Navbar Link</a></li>
        </ul>
        <a href="#" data-target="nav-mobile" class="sidenav-trigger"><i class="material-icons">menu</i></a>
    </div>
</nav>

As you can see, there are two identical sections defined for menu items. One for larger screens and one for smaller ones. In ASP.NET MVC I could do this:

<nav class="white" role="navigation">
    <div class="nav-wrapper container">
        <a id="logo-container" href="#" class="brand-logo">Logo</a>
        <ul class="left hide-on-med-and-down">
            @Menu()
        </ul>
        <ul id="nav-mobile" class="sidenav">
            @Menu()
        </ul>
        <a href="#" data-target="nav-mobile" class="sidenav-trigger"><i class="material-icons">menu</i></a>
    </div>
</nav>

@helper Menu() {
    <li><a href="#">Navbar Link</a></li>
}

In other words, I could use @helper to get HTML reusage INSIDE one and only one view.

However, as much as I know this is removed in ASP.NET Core MVC. What can I do to get to the same result?

4
  • Is it not the same as Partial Views? Commented Apr 14, 2018 at 13:28
  • @Thangadurai, Partial Views are defined in external files. In this case, encapsulation and self-containment is better. Commented Apr 14, 2018 at 13:39
  • @mohammadrostamisiahgeli What solution did you find to re-use HTML code inside view? Commented Jan 22, 2020 at 8:29
  • using old @Html.Partial. Commented Feb 17, 2020 at 10:07

1 Answer 1

2

You can do something like this.

@{
   Func<System.Collections.Generic.IEnumerable<string>, Microsoft.AspNetCore.Html.IHtmlContent> Menu = @<ul>
   @foreach (var menuEntry in item)
   {
       <li><a href="@menuEntry">@menuEntry</a></li>
   }
   </ul>;
}

And you can use the menu function like this.

@Menu(new[]{"Home","About"})

https://github.com/aspnet/Razor/issues/715#issuecomment-299342376 - It is mentioned here that, ASP.NET Team don't have any plans to do the @helper implementation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.