views:

343

answers:

3

Is there a shorter version of the following:

Using ASP.NET MVC, this is in the HTML page

<%= IsTrue ? Html.Image("~/images/myimage.gif") : "" %>

I know I'm only really writing 3 extra characters, just wondering if there is something better.

+6  A: 

No there is not, the ? operator is itself a short hand for the if else statement.

Robban
The conditional operator can only be used as an expression, while `if` is obviously a statement. One is not short hand for the other as they are conceptually different.
Thorarin
+1  A: 

Not for the case you outlined.

If you are doing a null check on A you could write var b = A ?? string.Empty;

Kindness,

Dan

Daniel Elliott
This one is handy when passing model to strongly typed partial because if null is provided - partial automagically receives model from view.
Arnis L.
+8  A: 

It might be acceptable to create html helper:

public static string ImageIf(this HtmlHelper helper, condition, url){
    return condition ? helper.Image(url) : "";
}

usage:

<%= Html.ImageIf(IsTrue, "~/images/myimage.gif") %>
Arnis L.