Call method from MVC view not working

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

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

      

and this is 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 was never a trigger, any hint? You need to consult.

+3


source to share


3 answers


Your ReadFile()

controller method 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 the File () method of the base ActionResult class to send the content to the caller.



So, you can use it in your view like so:

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

      

+2


source


Your controller method should look like this.

[HttpGet]
public ActionResult ReadFile(string path)
{

    return new FileContentResult(System.IO.File.ReadAllBytes(Server.MapPath(path)), "image");
}

      



The code is fine. But make sure your image path is like "~ \ Images \ Test.png"; The breakpoint in the controller will now be removed. It will be removed when the page is loaded into the client browser.

0


source


public FileContentResult getImage(int id)
{
    byte[] imgBytes = System.IO.File.ReadAllBytes(path);
    if (imgBytes!= null)
    {
        return new FileContentResult(imgBytes, "image/jpeg");
    }
    else
    {
        return null;
    }
}

      

On a razor

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

      

0


source







All Articles