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

4

7

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.

Adao answered 22/4, 2013 at 8:25 Comment(3)
So, is it during the page load or some on demand request to server ?Balmacaan
The image most probably will be kept on a Server, but the page content should be collected from the database before the page is loaded so I guess it is during page load.Adao
It's a form with images that someone has already created and I just have to redraw it when the user asks for it.Adao
M
5

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.

Mong answered 22/4, 2013 at 8:33 Comment(2)
I see. Was expecting something a bit easier but guess it is what it is. ThanksAdao
You're welcome. That's the easiest way of doing it, IMO, and solves your sort of problem generally. But there is a much better way of doing it that involves a bit of setup, using image resizer tools. Tools that will make sure your images are served in the most efficient way.Mong
G
5

Try this:

ViewBag.Logo = Url.Content("~/Content/Images/Logo.png");
Guadalupeguadeloupe answered 22/4, 2013 at 8:46 Comment(1)
I share your codes on my blog: zinzinzibidi.com/blog/genel/… Thanks a lot!!!Spermatophyte
Y
4

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 })" />
Yachting answered 22/4, 2013 at 8:28 Comment(0)
S
1
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>
Soubriquet answered 22/4, 2013 at 8:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.