C# ASP.NET MVC: Single-Line If Clause in View?

2020-07-26 02:34发布

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条回答
祖国的老花朵
2楼-- · 2020-07-26 03:35

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.

查看更多
▲ chillily
3楼-- · 2020-07-26 03:39
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.

查看更多
倾城 Initia
4楼-- · 2020-07-26 03:40

Try:

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

or

<% if(!Model.DisplayText) Response.Write(Model.MyText); %>
查看更多
登录 后发表回答