【问题标题】:How do I construct an if statement within a MVC View如何在 MVC 视图中构造 if 语句
【发布时间】:2011-06-02 05:05:04
【问题描述】:

希望这个问题快速而轻松

我有一个 mvc 视图,我想根据 if 语句显示两个值之一。这就是我在视图本身中所拥有的:

 <%if (model.CountryId == model.CountryId) %>
        <%= Html.Encode(model.LocalComment)%> 
        <%= Html.Encode(model.IntComment)%>

如果为真则显示model.LocalComment,如果为假则显示model.IntComment。

这不起作用,因为我同时显示了两个值。我做错了什么?

【问题讨论】:

  • 与一般的 C# 代码一样,您不应编写没有大括号的 if 语句 - {...}

标签: asp.net-mvc asp.net-mvc-2 view


【解决方案1】:

您的if 语句始终评估为真。您正在测试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) %>
<% } %>

显然您需要将12 替换为正确的值。

我个人会为此任务编写一个 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;
}

然后在你看来很简单:

<%= Html.Comment() %>

【讨论】:

    【解决方案2】:

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

    <%= Html.Encode(model.CountryId == 1 ? model.LocalComment : model.IntComment) %>
    

    (当然,根据您的真实条件进行调整。)

    我个人觉得这比&lt;% %&gt;&lt;%= %&gt; 的大混合更容易阅读。

    【讨论】:

    • +1 表示经常被忽视的条件运算符。空合并运算符 - ?? - 也非常有用。
    【解决方案3】:

    Conditional Rendering in Asp.Net MVC Views

     <% if(customer.Type == CustomerType.Affiliate) %>
       <%= this.Html.Image("~/Content/Images/customer_affiliate_icon.jpg")%>
     <% else if(customer.Type == CustomerType.Preferred) %>
       <%= this.Html.Image("~/Content/Images/customer_preferred_icon.jpg")%>
     <% else %>
       <%= this.Html.Image("~/Content/Images/customer_regular_icon.jpg")%>  
    

    【讨论】:

    • 这是一个黑客。一个肮脏、可怕的黑客,只是试图隐藏代码气味。
    • @Dan 来吧,“hack”在这里有点强。它是一个灰色区域——控制器是否应该知道处理这种情况可能对视图来说很困难?视图的需求是否应该由新的扩展方法来处理?我会称之为丑陋且难以维护,但我不会称之为糟糕的黑客攻击。
    • 一种扩展方法,不可避免地迫使用户编写更多 HTML,从而导致可读性和可维护性降低。不,我认为“hack”是一个公平的评价!
    猜你喜欢
    • 2017-07-08
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    相关资源
    最近更新 更多