Avrohom Yisroel
Avrohom Yisroel

Reputation: 9472

How do I use an image returned from an MVC controller in HTML?

I have an ASP.NET MVC project, that has a controller method that returns an image...

public ActionResult SpeakerImage(int id) {
  Speaker speaker = _speakersServiceLogic.GetByID(id);
  if (speaker != null) {
    return File(speaker.Picture, "image/jpg");
  }
  return null;
}

How do I use this in an HTML img tag? I know I can hard-code the src attribute...

<img src="/Speakers/SpeakerImage/@Model.ID" />

...but this will break if the controller action is moved.

I was wondering if there is a better way to do this. To create a link, I can use Html.ActionLink, which will create the HTML for me. Is there something similar for <img>?

Upvotes: 1

Views: 808

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157116

You can use Url.Action to generate the URL for you:

<img src='@Url.Action("Speakers", "SpeakerImage", new { ID = @Model.ID} )' />

Upvotes: 4

Related Questions