Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method from MVC view does not work

I am familiar with C# / .net, but pretty new with .net mvc and razor things, what I am trying to do is, that I want to call a method in a controller from the view to render the string path as binary, so i do this in the view :

<img src="@Url.Action("ReadFile", "FLK",  new { path = Model.Pict })" />

and this in the controller :

public void ReadFile(string path)
{
    Response.ContentType = "image";
    Response.BinaryWrite(System.IO.File.ReadAllBytes(path));
}

but when I put a debug point in the controller, my debug point never trigerred, any clue? Need some advice thank you.

like image 837
NomNomNom Avatar asked Aug 13 '26 17:08

NomNomNom


1 Answers

Your ReadFile() method in the controller should be something like this -

public ActionResult ReadFile(string path)
{
    byte[] imgBytes = System.IO.File.ReadAllBytes(path);
    return File(imgBytes, "image/png"); 
}

Here, your action method reads the image file into a byte array and then uses File() method of the ActionResult base class to send the contents to the caller.

So you can use it in your View like this -

<img src='@Url.Action("ReadFile", new { path = Model.Pict }))'/>
like image 100
Krishnraj Rana Avatar answered Aug 15 '26 09:08

Krishnraj Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!