Reputation: 1421
How can I display a default image if a user doesn't have an image? For now, I display like this:
<img alt="<%: Model.FullName %>" src="/Uploads/foto_<%: Model.StudentID %>.jpg"
style="height: 125px; width: 125px" />
And in some cases if I don't have this photo in Uploads folder I don't get an image, so I need a default image.
Upvotes: 1
Views: 1970
Reputation: 5800
Use the below code in your .aspx page
<asp:Image ID="Image1" runat="server" Height="125px" Width="125px" onerror="this.onload = null; this.src='profimgs/default_l.jpg';"/>
in your .cs page use the following
Image1.ImageUrl = "D:\profimgs\orginalimg.jpg";
Upvotes: 1
Reputation: 1038720
I would write an HTML helper:
public static class HtmlExtensions
{
public static MvcHtmlString StudentImage(this HtmlHelper<StudentViewModel> htmlHelper)
{
var model = htmlHelper.ViewData.Model;
var relativeImagePath = "~/uploads/foto_" + model.StudentID + ".jpg";
var imagePath = htmlHelper.ViewContext.HttpContext.Server.MapPath(relativeImagePath);
var image = new TagBuilder("img");
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
image.Attributes["src"] = urlHelper.Content("~/uploads/some_generic_image.jpg");
image.Attributes["alt"] = model.FullName;
image.Attributes["style"] = "height: 125px; width: 125px";
if (File.Exists(imagePath))
{
image.Attributes["src"] = urlHelper.Content(relativeImagePath);
}
return MvcHtmlString.Create(image.ToString());
}
}
and then in your view simply:
<%= Html.StudentImage() %>
Upvotes: 0