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 ?

Gab
  • 1,861
  • 5
  • 26
  • 39
  • 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" – Adriano Repetti May 13 '14 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 – MilkyWayJoe May 13 '14 at 14:14
  • See http://stackoverflow.com/questions/9399531/asp-net-mvc-razor-conditional-attribute-in-html and http://stackoverflow.com/questions/8061647/conditional-html-attributes-using-razor-mvc3 for couple options, you could also just have two different `img` tags, one in the if and one in an else for each case – AaronLS May 13 '14 at 14:15

1 Answers1

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

    <img src="@source" />
leskovar
  • 661
  • 3
  • 8
  • Depending on the context you probably need to wrap the variable declaration `@{ var source= "~/Content/images/header-logo.png"; }` – AaronLS May 13 '14 at 14:16
  • Thanks. I have a null reference exception with "@if(Model.HavePhoto)" but otherwise your solution seems to work. – Gab May 13 '14 at 14:25