4

I try to reuse HTML snippets in my razor page (view component) but somehow it never call or hit the break in the html section.

I'm using Asp.net core 2.2

        @{
        Func<CategorySimpleModel, Microsoft.AspNetCore.Html.IHtmlContent> DisplayManufacturerPicture=
            @<div class="col-sm-4">
                <div class="row">
                    @foreach (var m in item.Manufacturers)
                    {
                        <div class="col-md-6 col-sm-12">
                            blah blah
                        </div>
                    }
                </div>
            </div>;
        }

   @foreach (var root in Model.Categories)
            { 
               DisplayManufacturerPicture (root);
            }
4
  • You might want to check out Razor components Commented Mar 19, 2019 at 10:23
  • that's .net core 3.0 preview, I'm using 2.2 only. Commented Mar 19, 2019 at 10:24
  • "but somehow it never call or hit the break in the html section" What exactly do you mean? Did you place a breakpoint inside the Func and it's not getting hit? Commented Mar 19, 2019 at 10:29
  • yes it never hits and I've even tried with a simple string func<string, IHtmlContent>. strangely it never shows anything though for loop does hit DisplayManufacturerPicture Commented Mar 19, 2019 at 10:35

2 Answers 2

2

somehow it only works with @ though the method call is inside the server side syntax

 @if (root.Manufacturers.Count > 0)
{
   @DisplayManufacturerPicture(root);
}
Sign up to request clarification or add additional context in comments.

Comments

1

What you are trying to do is not (yet) possible. You should take a look at partial views instead:

@foreach (var root in Model.Categories)
{
    <partial name="_DisplayManufacturerPicture" model="root" />
}

And then inside _DisplayManufacturerPicture.cshtml:

@model CategorySimpleModel

<div class="col-sm-4">
    <div class="row">
        @foreach (var m in item.Manufacturers)
        {
            <div class="col-md-6 col-sm-12">
                blah blah
            </div>
        }
    </div>
</div>

2 Comments

yes I do use a lot of partial view, what I'm trying to do is the way to replace legacy @helper from old asp.net. You may see dotnetthoughts.net/how-to-reuse-html-snippets-in-cshtml-view or stackoverflow.com/questions/32331157/…
Partial views are not legacy and also note that I am not using the HtmlHelper either. And none of this is “old ASP.NET”.

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.