user3015384
user3015384

Reputation: 73

Can you use a controller action to either return an image or a url string

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?

Upvotes: 0

Views: 331

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239250

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.

Upvotes: 1

Related Questions