0

I'm a beginner with ASP.NET MVC and I'm trying to set the src of an image with razor in a asp.net MVC website using an If statement.

this code works :

 <img src="@Url.Action("GetPersonPhoto", "Home", new RouteValueDictionary( new { cardid = "696969" }) )" />

I want to add :

@if(Model.HavePhoto)

And set the src to :

"~/Content/images/header-logo.png"

if HavePhoto is false...

How can I do it ?

3
  • RT(F)M. Ok, to be serious...google any example. Image source itself shouldn't be IMO inside your cshtml page but decided in controller and stored in model src="@Model.PhotoUrl" Commented May 13, 2014 at 14:14
  • I would have the GetPersonPhoto action decide which image to use and handle cases where Model.HavePhoto are false, providing the url of a default image, as oppose to handle this in the view layer Commented May 13, 2014 at 14:14
  • See stackoverflow.com/questions/9399531/… and stackoverflow.com/questions/8061647/… for couple options, you could also just have two different img tags, one in the if and one in an else for each case Commented May 13, 2014 at 14:15

1 Answer 1

2
    var source= "~/Content/images/header-logo.png";
    @if(Model.HavePhoto)
    {
       source= Url.Action("GetPersonPhoto", "Home", 
                   new RouteValueDictionary( new { cardid = "696969" }))
    }

    <img src="@source" />
Sign up to request clarification or add additional context in comments.

2 Comments

Depending on the context you probably need to wrap the variable declaration @{ var source= "~/Content/images/header-logo.png"; }
Thanks. I have a null reference exception with "@if(Model.HavePhoto)" but otherwise your solution seems to work.

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.