2

I got a trivial issue.. and can't solve it.

I have this in my view:

<% if (!Model.DisplayText) { %> <%= Model.MyText %> <% } %>

As you can see, i am using 3x <% and %>. That just screams like bad code. But I can't seem to get this working in a single line. This throws all kinds of weird errors (such as semicolon missing, and when I add one it throws something else):

<% if (!Model.DisplayText) { Model.MyText } %>

Any idea?!

3
  • one of them actually writes to view content... that's your problem. Commented Jul 22, 2009 at 23:44
  • 2
    Just a note, the reason you're running into a no semicolon issue is because unlike "<%" which is for inline code, the "<%=" is for output and likely is transformed into a method call (something like page.write(Model.MyText);) when the page is parsed. Commented Jul 22, 2009 at 23:52
  • Your original code was fine. There is nothing inherently wrong with 3x <% %>'s. Just aim for clarity Commented Jul 23, 2009 at 0:54

3 Answers 3

11

Try:

<%= Model.DisplayText ? "" : Model.MyText %>

or

<% if(!Model.DisplayText) Response.Write(Model.MyText); %>
Sign up to request clarification or add additional context in comments.

2 Comments

Beaten to the punch, nice post.
The ternary operator solution was exactly what I needed. Thank you! P.S. In that case there wouldn't be a semicolon so you may want to remove that for others that look up this solution. Thanks again!
1
is basically like writing Response.Write(your data) means the code will execute, but it's not going to specifically write anything out. You could use a Response.Write inside your if block to output the data you want.

Or go with OrbMan's answer, he beat me to it.

1 Comment

All answers were great :) Thank you!
1

This:

 <%= foo %>

is generally equivalent to:

 <% Response.Write(foo) %>

So you can write:

 <% if (!Model.DisplayText) { Response.Write(Model.MyText); } %>

but I don't see what you really get from this. Your original code is fine as it is. Or you might use the ternary operator, as OrbMan suggests.

1 Comment

You're missing a semi-colon after the call to Response.Write at the least, and this is probably a case where the brackets would best be left out.

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.