How to display a default image in case the source does not exists in MvC View

I have following code in loginpartial.cshtml file
Can anyone advice if there is a way to display a default image if the src does not exists?

@if (Request.IsAuthenticated)
{   

    <li><a href="#">Support</a></li>
    <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">



        //in below image tab m Display user Uploaded image ,
        //wants to display default Image if no Image is present

        <img src="/user/RetrievePhoto/@ABC.Web.Session.LoginData.UserToken.UserId" alt="" class="profilePhotoSM" />@ABC.Web.Session.LoginData.UserToken.UserName <span class="caret"></span></a>
        <ul class="dropdown-menu">
            <li>@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
                {
                @Html.AntiForgeryToken()
                <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
                }</li>
        </ul>
    </li>


}
else
{

    <li>@Html.ActionLink("Sign Up", "Register", "User", routeValues: null, htmlAttributes: new { id = "registerLink", @class = "navLink" })</li>
    <li>@Html.ActionLink("Login", "Authentication", "Account", routeValues: null, htmlAttributes: new { id = "loginLink", @class = "navLink" })</li>

}

Upvotes: 3

Views: 1782

Answers (1)

hutchonoid
hutchonoid

Reputation: 33306

Add a default image to your web server i.e. myDefaultImage.png. Add an ImageName and Photo properties to your model i.e.

public class AModel
{
   public string ImageName { get; set; }
   public string Photo { get { return ImageName == null ? "myDefaultImage.png" : ImageName; }}
}

Set the ImageName property from your controller if the image exists. The get in the Photo property will handle the default image if it is not set.

You can then show the src as follows:

src="/user/RetrievePhoto/@Model.Photo"

Upvotes: 4

Related Questions