在视图条件语句 [英] Conditionals in Views

查看:135
本文介绍了在视图条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的ASP MVC和不知道是什么来处理你的看法条件语句的最好方法?我相信没有一个一刀切的办法,但对于简单的检查是明智的,有IF-THEN-ELSE语句乱抛垃圾的看法?

I am fairly new to ASP MVC and was wondering what is the best way to handle conditional statements in your views? I am sure there isn't a one size fits all approach, but for simple checks is it wise to have If-Then-Else statements littering the view?

例如,说我有一个名单,并希望如果模型属性中的一个设置来设置列表项目之一的类。

For example, say I have a list and wish to set the class on one of the list items if one of the model properties is set.

<% if (myModel.MyProperty == 1) { %>
   <li class="myClass">
<% } else { %>
   <li>
<% } %>

这是接近最好的方法,还是有更好的办法?我只是担心,如果你有大量的条件语句像这样在你看来这是要开始寻找pretty凌乱。

Is this the best way to approach this, or is there a better way? I am just concerned that if you have numerous conditionals like this in your view it is going to start to look pretty messy.

在此先感谢您的任何建议。

Thanks in advance for any advice.

推荐答案

如果你真的想要一个更清洁的观点,你可以创建一个帮手:

If you really want a cleaner view, you could create a helper:

public static class MyHelpers {
    // Need a more descriptive name (based on what you're generating)
    public static string MyListItemHelper(this HtmlHelper helper, bool condition) {
        if(condition) {
            return "<li class=\"myClass\">";
        } else {
            return "<li>";
        }
    }
}

那么你的观点仅仅是:

Then your view is just:

<%= Html.MyListItemHelper(myModel.MyProperty == 1) %>
    ...
</li>

这篇关于在视图条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆