Introduction
This article will help you to return an Image from
ASP.NET MVC Controller. In this article, I will use the base controllers File Method.
Let's create one empty MVC project. To create empty MVC project you can follow the below steps:
- Open Visual Studio
- Select on File, New, then click Project or CTRL + SHIFT + N,
- Now one dialog box will open from that dialog box. Select Installed Template, Visual C#, then click Web and select ASP.NET Web Application Project.
- Provide the name for project and click OK.
- Now one more dialog box will open and from that select Empty Project and check MVC Checkbox and press OK.
After creating MVC project, open Solution Explorer and add new empty controller. To add new controller, right click on the controller and select Add, then click Controller and create empty controller. I am creating a HomeController.
My Controller Code looks like the following,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace Returning_Image_From_Controller.Controllers
- {
- public class HomeController : Controller
- {
-
-
- public ActionResult Index()
- {
- return View();
- }
- }
- }
Now, I am creating one folder where I am putting some images. I am adding folder with name "Images" and also adding some JPEG images.
After adding folder in my project I am creating one more action method in my home controller with name "GetImage" and I am writing the following code in GetImage action method.
- public ActionResult GetImage(string id)
- {
- var dir = Server.MapPath("/Images");
- var path = Path.Combine(dir, id + ".jpg");
- return base.File(path, "image/jpeg");
- }
In above code I am using base controllers file method.
Now, I am adding one View for my Index action and write the following code in Index.cshtml,
- @{
- Layout = null;
- }
-
- <h2>Great Personalities</h2>
- <ul>
- <li><a href="~/Home/GetImage/1">APJ Abdul Kalam</a> </li>
- <li><a href="~/Home/GetImage/2">Bill Gates</a> </li>
- <li><a href="~/Home/GetImage/3">Mark Zuckerberg</a> </li>
- <li><a href="~/Home/GetImage/4">Steve Jobs</a></li>
- </ul>
Let's run the Application and you will get the following output.
Output
Read more articles on ASP.NET: