Pass image from controller and display in a view using ViewBag in ASP.NET MVC 3

Leron_says_get_back_Monica picture Leron_says_get_back_Monica · Apr 22, 2013 · Viewed 23.7k times · Source

I guess it's something very straight forward but I can't find out how to do it. In my controller I have:

 public ViewResult ShowForm()
        {
            ViewBag.Title = Resources.ApplicationTitle;
            ViewBag.LabelStatus = Resources.Status;
            //Logo
            ViewBag.Logo =@"C:\Images\Logo.png";
            return View("ShowForm");
        }

And in my view I try this:

<div id="drawForm">
<img src="@ViewBag.Logo" alt="Logo" />    
</div>

However when I run this I just get the "Logo" text.

Answer

von v. picture von v. · Apr 22, 2013

Use Server.MapPath to get the correct path of the image. Suppose your images folder is inside the Content folder that is normally included in an MVC project. You can do something like this:

public ViewResult ShowForm()
{
    //Logo
    ViewBag.Logo = Server.MapPath("~") + @"Content\Images\Logo.png";
    return View("ShowForm");
}

And you don't have to change the code in your view.