如何在 MVC 视图中构造 if 语句
希望这个问题快速且轻松,
我有一个 mvc 视图,我想根据 if 语句显示两个值之一。这就是我在视图本身中的内容:
<%if (model.CountryId == model.CountryId) %>
<%= Html.Encode(model.LocalComment)%>
<%= Html.Encode(model.IntComment)%>
如果 true 显示 model.LocalComment,如果 false 显示 model.IntComment。
这不起作用,因为我显示了两个值。我做错了什么?
Hopefully this question is quick and painless
I have a mvc view where i want to display either one of two values depending on an if statement. This is what I have in the view itself:
<%if (model.CountryId == model.CountryId) %>
<%= Html.Encode(model.LocalComment)%>
<%= Html.Encode(model.IntComment)%>
If true display model.LocalComment, if false display model.IntComment.
This doesn't work as I get both values showing. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
if
语句的计算结果始终为 true。您正在测试model.CountryId
是否等于model.CountryId
,这始终为 true:if (model.CountryId == model.CountryId)
。此外,您还缺少else
语句。它应该是这样的:显然你需要用正确的值替换
1
和2
。就我个人而言,我会为此任务编写一个 HTML 帮助器,以避免视图中出现标签汤:
然后在您的视图中简单地:
Your
if
statement always evaluates to true. You are testing whethermodel.CountryId
equalsmodel.CountryId
which is always true:if (model.CountryId == model.CountryId)
. Also you are missing anelse
statement. It should be like this:Obviously you need to replace
1
and2
with the proper values.Personally I would write an HTML helper for this task to avoid the tag soup in the views:
And then in your view simply:
除了达林关于条件始终为真的观点之外,您可能还需要考虑使用条件运算符:(
当然,根据您的真实条件进行调整。)
就我个人而言,我发现这比
<% %>
和<%= %>
的大混合物。Aside from Darin's point about the condition always being true, you might want to consider using the conditional operator:
(Adjust for whatever your real condition would be, of course.)
Personally I find this easier to read than the big mixture of
<% %>
and<%= %>
.Asp.Net MVC 视图中的条件渲染
Conditional Rendering in Asp.Net MVC Views