How do I share @functions across View Pages in .net core?

Viewed 297

I have a function in my View called DisplayImage() that works great

@foreach (var x in Model)
{
    @Html.Raw(@DisplayImage(x.FrontFileName))
}

@functions {
    public static string DisplayImage(string bagname)
    {
            string img = "http://www.airsicknessbags.com/images/" + bagname + ".jpg";
            string result = "<a href=" + img + " target=\"_blank\">";
            result += "<img src=" + img + " style=\"width: 100px\" />";
            result += "</a>";
            return (result);
    }
}

Another page also needs DisplayImage. Instead of duplicating the code in each View, how do I put (and call) the code from a single place?

I've seen that you can do this with HTML helpers in the App_Code directory of earlier versions of MVC, but I'm using .net Core 3.1. I've tried RenderSection in both the _Layout.cshtml and in my View page, but I can't seem to get it right.

0 Answers
Related