views:

514

answers:

3

Should I create a related view for each condition in my controller? e.g. I have the following code

public ActionResult List(){

 List<Report> reports = getReport();
 if(report.Count > 0){
 //returning the normal view
return View();
}else{
//show the view for no reports
return View("NoReportAvailable");
}

}

or i can also have only one view (the List.aspx) and do if else in my view, maybe render partial view "NoReportAvailablePartial" in case of 0 reports.

which one is better, or how do you guy deal with this scenario?

+2  A: 

I prefer a single view if the logic inside mainly deals with hiding out sections that are empty.

If there are however bigger differences, for example, extra information or controls for users in different roles, then it might be a good idea to arrange for specific views to keep views clear.

Developer Art
+4  A: 

It depends on what other HTML or logic the view contains but I tend to follow these rough rules:

  • If you find your views are starting to contain a lot of if/else logic then it should probably be refactored into separate views and the logic placed in the controller.

  • If your view contains no other repeatable HTML apart from the if logic (i.e. the list or the 'no report available') then I would separate to 2 views and place the logic in the controller. E.g. If you're using Master pages that contain the rest of the HTML. I think it makes it clearer.

  • If your page contains a lot of HTML that would be duplicated if the views are separated then I would put the if logic in the view and render a partial view depending on whether the list has items or not.

I believe that basic display logic (e.g. if (report.Count > 0) {}) is okay in the view but you should stick the DRY principal and your view should not become littered with code.

David G
+2  A: 

Remember what each part of the MVC pattern should be responsible for; the Views should only show stuff, while the Controller should decide what stuff is to be shown.

I would definitely go for two different views - one of them will be responsible for rendering a list of items, and one will be responsible for rendering an error message. Those are two entirely different things, and the Controller should make the decision on what should be rendered, not the view.

Tomas Lycken