0

I've got a list of data that I need to display. Each item has an image field that is pulled from the database.

If the image is null it needs to display a random stock image from the server.

I wanted to do something like:

<img src='@Url.Action("GetImage", "MeetTheTeam", new { id = TeamMate.Id })' />     

and then in the controller:

public ActionResult GetImage(int id)
    {
        var item = team.Where(teammate => teammate.Id == id).SingleOrDefault();

        if (item.Image != null)
        {
            return File(item.Image, "image/jpg");
        }
        else
        {                
            return Content(AppSettings.AppRoot + "content/images/MeetTheTeam/v2/gray-block" + random.Next(1, 14) + ".jpg");
        }
    }

But this is not working, and I can't debug into the controller...

Is this even possible?

  • You say it's not working: how exactly? What's the result? And **why** can't you debug inside the controller? – chiapa Oct 14 '14 at 15:43
  • What is the proper type of your Image? How do you store in DB? You may make a mistake looking for a null value but probably there is a simple empty string. And by the way, you can debug. – Shmwel Oct 14 '14 at 15:45
  • I would think this would give a compile time error as well. I don't see an implicit conversion method between File and ActionResult. – Joel Etherton Oct 14 '14 at 16:00
  • the image is type image in the database and it can be null. No compile error. When I say I can't debug I mean breakpoints do not get hit. – user3015384 Oct 14 '14 at 16:03

1 Answers1

1

You can't return either a stream or a string. Url.Action will merely print out the URL to this resource, which the client's browser will then use to fetch the image. In the case of an existing image, you return a image file stream, which the browser will happy render as an image, but in the case of the fallback, you're returning just text, which the browser will also try (and fail) to interpret as an image.

You have two choices:

  1. Instead of returning Content, return Redirect with the URL to the image passed. That will cause the browser to try to load that URL instead, resulting in a good image stream.

  2. Open the fallback image from the file system and then return the stream just as you're doing with the image loaded from the database.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444