Razor Pages return an Image in handler to an ``<img>`` element

Viewed 935

In MVC, we can return an image at controller using:

[HttpGet]
public ActionResult LoadImageFile(string name)
{
    byte[] Buf = System.IO.ReadAllBytes(name);
    return File(Buf, "image/png");
}

And then in my cshtml

<img src="@Url.Content("~/myController/LoadImageFile")?name=test.jpg" />

May I know how can I do that in Razor Pages handler? I am trying something like this below and it doesn't work:

public IActionResult OnGetLoadImageFile(string name)
{
    byte[] Buf = System.IO.ReadAllBytes(name);
    return File(Buf, "image/png", name);
}

<img src="@Url.Page("~/myPage", "LoadImageFile")?name=test.png" />
1 Answers

If LoadImageFile handler is in Pages/Index.cshtml.cs,your url should be like below:

<img src="@Url.Page("Index","LoadImageFile",new {name="test.jpg" })" />

Or:

<img src="@Url.Page("/Index","LoadImageFile",new {name="test.jpg" })" />

If LoadImageFile handler is in Pages/FolderName/Index.cshtml.cs,your url should be like below:

<img src="@Url.Page("FolderName/Index","LoadImageFile",new {name="test.jpg" })" />

Or:

<img src="@Url.Page("/FolderName/Index","LoadImageFile",new {name="test.jpg" })" />
Related