Raju
Raju

Reputation: 114

How to display external image in MVC 3

My controller returns a string which is a url of an image of an external site. How do I display that url on the view. I appreciate your help.

Upvotes: 0

Views: 1286

Answers (3)

teh4x
teh4x

Reputation: 491

Perhaps you're missing the part where you have to HTML-encode your output with the <%: %> tag, a la:

<%: Html.Label(ViewData["PicUrl"].ToString()) %>

...or, if it's a string property on your model...

<label><%: Model.PicUrl %></label>

Upvotes: 0

Shyju
Shyju

Reputation: 218722

AngryHacker is correct. I am just expanding AngryHacker's answer with some code example.

Add a property in your ViewModel for the image url and return it in the first get call. Then use it in the View. Thus you are avoiding an unnecessary http request to to the action again

public class UserProfileViewModel
{
  public string DisplayName { set;get;}
  public string GravatarURL { set;get;}
}

and in your ACtionMethod,

public ActionResult Get(int id)
{
  UserProfileViewModel objVm=new UserProfileViewModel();
  objVM.GravatarURL="http://www.externalsite.com/image/tiyra.jog";
  //Set other properties also.

  return View(objVm);
}

and in the View which is strongly typed to your UserProfileViewModel,

@model UserProfileViewModel
<h2>"@Model.DisplayName </h2>
<img src="@Model.GravatarURL" />
<p>The image is loaded from @Model.GravatarURL</p>

Upvotes: 2

AngryHacker
AngryHacker

Reputation: 61606

Make the URL part of your model and just reference it in the View.

Upvotes: 0

Related Questions