1

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.

2 Answers 2

1

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";
Sign up to request clarification or add additional context in comments.

2 Comments

If you have any doubts feel free to ask more.
If you don't have image in your root folder its better to retrieve a image via web link to your page. Hope this solves your problem
0

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() %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.