如何在MVC视图中构造if语句

Cun*_*ers 9 asp.net-mvc view asp.net-mvc-2

希望这个问题快速无痛

我有一个mvc视图,我想根据if语句显示两个值中的任何一个.这就是我在视图中所拥有的:

 <%if (model.CountryId == model.CountryId) %>
        <%= Html.Encode(model.LocalComment)%> 
        <%= Html.Encode(model.IntComment)%>
Run Code Online (Sandbox Code Playgroud)

如果为true,则显示model.LocalComment,如果为false显示模型.IntComment.

这不起作用,因为我显示了两个值.我究竟做错了什么?

Dar*_*rov 11

您的if语句始终评估为true.你正在测试是否model.CountryId等于model.CountryId总是如此:if (model.CountryId == model.CountryId).你也错过了一个else陈述.它应该是这样的:

<%if (model.CountryId == 1) { %>
    <%= Html.Encode(model.LocalComment) %> 
<% } else if (model.CountryId == 2) { %>
    <%= Html.Encode(model.IntComment) %>
<% } %>
Run Code Online (Sandbox Code Playgroud)

显然,你需要更换1,并2用正确的价值观.

就个人而言,我会为此任务编写一个HTML帮助程序,以避免视图中的标记汤:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后在您的视图中简单地说:

<%= Html.Comment() %>
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 6

除了Darin关于条件始终为真的观点之外,您可能还需要考虑使用条件运算符:

<%= Html.Encode(model.CountryId == 1 ? model.LocalComment : model.IntComment) %>
Run Code Online (Sandbox Code Playgroud)

(当然,请根据您的实际情况进行调整.)

我个人觉得这更容易比的大混合读取<% %><%= %>.