user3929884 user3929884 - 1 year ago 81
C# Question

Display Image from ViewData

Can you help me with a problem loading an Image from a ViewData?
In my model I load an image from the server by company name:

System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Server.MapPath("~/Logos/"+ companyName +".png"))

I load this Image into a Viewdata:

ViewData["Image"] = image;

I return it to the View and there I want to load that Image again with:

<img src=@ViewData["Image"] alt="" />

The image is not displayed. Can you help me with that problem?

Answer Source

As such you are using MapPath in your code, I believe the image file is in the project source itself and not in binary format. You should use your image path like this in your view file, replace the path below with your path of the file in the project:

<img src="@Url.Content("~/Content/App/Images/filename.gif")" alt="Loading..." />

or like this:

In Controller:

public ActionResult Action1(){
 ViewData.CompanyName = "C1"; // this value can be populated from anywhere.
 return View();

In View:

<img src="@Url.Content(String.Format("~/Logos/{0}.png", ViewData.CompanyName))" alt="Loading..." />

where ViewData.CompanyName is a string that is populated and then given to the view. You may also use a strongly typed class to create a model for your view instead of using ViewData.

And when this view will be rendered in browser, it will have this image provided the file is present in that location and you have the rights to view that resource.