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

2020-06-05 07:59发布

问题:

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?

回答1:

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



回答2:

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:

I think what you're referring to is a post by Rob Conery, where he mentions a rule he uses:

If there's an if, make a helper

So to answer your question, the idea is that if you find yourself needing to use if in your View, you should consider adding a helper extension method to render that part of your View instead.



回答4:

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.



回答5:

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



回答6:

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



回答7:

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