DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

11

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (3)

Collapse
 
suzijie860706 profile image
suzijie860706

thank you

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more