0

I'm trying to display an image in MVC by calling on a controller method in my view which returns the path of the image file to then be displayed.

Controller

static public string returnImgPath()
        {
            return "~/Users/orpi/Downloads/banff.jpg";
        }

View:

<img src="@Url.Action("returnImgPath", "OUsersController")" alt ="Image"/>

I don't believe I can do this using Url.Content because my model is based on a database using EF and so I can't use model functions/members to really do anything.

Displaza
  • 75
  • 7
  • Any reason why you have to return the image from the controller? Can you not just add the image as the source? – JamesS Dec 16 '19 at 11:50
  • What is the question here? Are you trying to show an image where the path is in the database or where the image data is inside the database? or something else? – lordvlad30 Dec 16 '19 at 11:54
  • @lordvlad30 the image is stored in a normal directory on my PC and that is what I'm trying to display to MVC – Displaza Dec 16 '19 at 15:09
  • @Displaza and using your current code the image does not display? Have you tried an absolute path (`C:\Users\...`) because the `~` points to the root of your application meaning that in your application is a folder called `Users`. – lordvlad30 Dec 16 '19 at 15:17
  • @lordvlad30 I have tried using an absolute path both in the ```returnImgPath``` method and also replacing the ```Url.Action``` with ```Url.Content``` and the absolute path in it's parameters. – Displaza Dec 16 '19 at 15:23
  • @Displaza Place another `` element under your current and place the complete path in there. Check if that works, if it does , check the difference, if it does not check the network tab (browser developer tools) and check what error the request for the image gives (not authorised, not found ...). – lordvlad30 Dec 16 '19 at 15:30
  • @lordvlad30 I've managed to fix it by placing the file in a folder contained within the solution rather than just my downloads folder but thank you for the advice. – Displaza Dec 17 '19 at 08:59
  • @Displaza So it was a permission issue. Glad you figured it out. – lordvlad30 Dec 17 '19 at 09:02

2 Answers2

0

I think 'URL.Content' can be used in MVC views and below link can help achieve the same: [link]: ASP MVC Friendly URL's and Relative Path Images. I believe this can be of some help.

Hemant Kumar
  • 186
  • 6
0

I believe this is what you are looking for.

<img src= "@Url.Content(Model.returnImgPath)" alt="Image" />

If you want to pass the url for a file path for the website then you can pass it using Url.Content.

Mazdaq
  • 53
  • 12
  • The problem is with using ```.Content``` is that because I'm using EF and a database as my model, the model in the view is of an IEnumerable data type and so I can't call on it very easily. – Displaza Dec 16 '19 at 15:12