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

后端 未结 7 1205
孤城傲影
孤城傲影 2021-02-10 05:47

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 a

7条回答
  •  星月不相逢
    2021-02-10 06:08

    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.

提交回复
热议问题