Florim Maxhuni
Florim Maxhuni

Reputation: 1421

asp net mvc default image display

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

Answers (2)

Karthik Malla
Karthik Malla

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

Darin Dimitrov
Darin Dimitrov

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

Related Questions