怎样构建一个如果一个MVC视图中陈述 [英] How do I construct an if statement within a MVC View
问题描述
希望这个问题是快速,无痛
Hopefully this question is quick and painless
我有,我想这取决于if语句,显示以下两个值中的一个MVC视图。这是我在视图本身:
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)%>
如果属实显示model.LocalComment,如有虚假显示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?
推荐答案
您如果
语句总是判断为真。您正在测试是否 model.CountryId
等于 model.CountryId
这始终是正确的:如果( model.CountryId == model.CountryId)
。你也是缺少其他
语句。它应该是这样的:
Your if
statement always evaluates to true. You are testing whether model.CountryId
equals model.CountryId
which is always true: if (model.CountryId == model.CountryId)
. Also you are missing an else
statement. It should be like this:
<%if (model.CountryId == 1) { %>
<%= Html.Encode(model.LocalComment) %>
<% } else if (model.CountryId == 2) { %>
<%= Html.Encode(model.IntComment) %>
<% } %>
显然,你需要替换 1
和 2
与正确的价值观。
个人而言,我会写一个HTML帮手这一任务,以避免在视图的标记汤:
Personally I would write an HTML helper for this task to avoid the tag soup in the views:
public static MvcHtmlString Comment(this HtmlHelper<YourModelType> htmlHelper)
{
var model = htmlHelper.ViewData.Model;
if (model.CountryId == 1)
{
return MvcHtmlString.Create(model.LocalComment);
}
else if (model.CountryId == 2)
{
return MvcHtmlString.Create(model.IntComment);
}
return MvcHtmlString.Empty;
}
然后在你看来简单:
And then in your view simply:
<%= Html.Comment() %>
这篇关于怎样构建一个如果一个MVC视图中陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!