“if” considered harmful in ASP.NET MVC View (.aspx

2020-06-05 07:54发布

I remember seeing a blog (or something) that said you should not use <% if ... %> in .aspx files in ASP.NET MVC, but I can't remember what it said the alternative is. Can anyone remember seeing this and point me to it?

7条回答
相关推荐>>
2楼-- · 2020-06-05 08:05

Basically what it means is that you shouldn't have huge if statements in your Views, your Controllers and ViewModels should be able to handle the logic. Example:

<h2 class="title">
    <% if (ViewData["category"] == null { %>
        All Products
    <% } else { % >
        <%= ViewData["category"] %>
    <% } %>
</h2>

Should be:

<h2 class="title>
    <%= Model.Title %>
</h2>

If your controllers and ViewModels can't handle the logic, you should write Html Helpers for more complicated logic (thus making it reusable and more readable).

<h2 class="title>
    <%= Html.GetPageTitle(Model.Category) %>
</h2>
查看更多
老娘就宠你
3楼-- · 2020-06-05 08:13

As i think the best approach for this is try to handle your if condition in controller and pass the specific view for required result or pass the View name in a variable to render.

public class HomeController :Controller
{
    public ActionResult Category(string? category)
    {
       View viewToReturn;
       if (category == null)
          viewToReturn = View("CategoryList", repo.GetAllCategory); /// it is a View
       else
          viewToReturn = View("Category", repo.GetCategory(category)); /// it is a View

       return viewToReturn;
    }
}

Well, Martin answer is also from best practices.

查看更多
爷、活的狠高调
4楼-- · 2020-06-05 08:15

I'm not sure if this is what you saw, but here is a blog that mentions it. See item #11.

查看更多
闹够了就滚
5楼-- · 2020-06-05 08:19

I suspect that the point was an attempt to avoid spaghetti code rather than restrict the use of "if"s, here is a link to a Rob Conery blog about this, he does actually mention using helpers instead of Ifs so this may be what you saw ASP.NET MVC: Avoiding Tag Soup

查看更多
We Are One
6楼-- · 2020-06-05 08:23

I feel that is just fine. It allows for the view to have control of its presentation.

查看更多
Animai°情兽
7楼-- · 2020-06-05 08:24

Is this the issue you're referring to?

binding expressions can not be used in statement block <% %>, just as statements can not be used in a binding expression block <%# %>

-- bruce (sqlwork.com)

"Jason" <> wrote in message news:23C11F83-A2AA-406D-BDEC-...

What is wrong with the following if statement in my aspx page?

"T" Then%>

I get error that says: BC30201: Expression expected.

Bruce Barker

查看更多
登录 后发表回答