Leron
Leron

Reputation: 9866

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

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.

Upvotes: 7

Views: 26133

Answers (4)

dss
dss

Reputation: 11

public ActionResult ShowForm()
        {
            ViewBag.Title = Resources.ApplicationTitle;
            ViewBag.LabelStatus = Resources.Status;
            //Logo
           byte[] imgbytes =  File.ReadAllBytes(@"C:\Images\Logo.png");
           return File(imgbytes , "image/png");
        }

<div id="drawForm">
<img src="controllerName/ShowForm" alt="Logo" />    
</div>

Upvotes: 1

karaxuna
karaxuna

Reputation: 26940

Try this:

ViewBag.Logo = Url.Content("~/Content/Images/Logo.png");

Upvotes: 5

DarthVader
DarthVader

Reputation: 55032

You need a ImageController to render that.

See this:

ASP.NET MVC3: Image loading through controller

and this: Can an ASP.NET MVC controller return an Image?

once you have a controller you can render as follows:

public class ImageController{

public ActionResult ShowImage(string path) 
{

    return File(path);
}

}

in your views:

<img src="@Url.Action("Render","Image", new {id =1  // or path })" />

Upvotes: 4

von v.
von v.

Reputation: 17108

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.

Upvotes: 5

Related Questions