DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Displaying images in asp net MVC

To display images in an ASP.NET MVC application, you can follow these steps:

  1. First, make sure you have the images stored in a directory within your project, such as the "Images" folder.

  2. In your MVC controller, create an action method that will retrieve the image file from the server and return it as a FileResult. The action method could look like this:

public ActionResult DisplayImage(string imageName)
    string imagePath = Server.MapPath("~/Images/" + imageName);
    return File(imagePath, "image/jpeg"); // Adjust the content type based on the image type
Enter fullscreen mode Exit fullscreen mode
  1. In your view, use the Url.Action helper method to generate the URL for the action method and specify the image name as a parameter. You can then use the generated URL as the source for the <img> tag:
<img src="@Url.Action("DisplayImage", "YourControllerName", new { imageName = "yourImage.jpg" })" alt="Image" />
Enter fullscreen mode Exit fullscreen mode

Replace "YourControllerName" with the name of your controller and "yourImage.jpg" with the actual image file name.

  1. When the view is rendered, the generated URL will point to the action method in the controller, which will retrieve the image file and return it to the browser.

Make sure that the image file exists in the specified location and that the correct content type is provided in the File method.

Remember to adjust the file paths and names according to your project's structure and naming conventions.

Top comments (3)

tomford profile image
tomford51 • Edited

Thanks for the clear and informative explanation of how to display images in ASP.NET MVC! I especially liked your approach to different display methods, which makes it easy to adapt my project to specific needs. This is invaluable for developers who want to make their web applications more dynamic and engaging. By the way, if you need quality images for your project, I can recommend Depositphotos. Not only do they offer a huge collection of photos, but they emphasize the importance of creativity and innovation in their work, which I think is important for any creative project.

sardarmudassaralikhan profile image
Sardar Mudassar Ali Khan

Thanks man

suzijie860706 profile image

thank you