View for each condition in ASP.Net MVC Controller

Should I create a linked view for each condition in my controller? for example 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 only have one view (List.aspx) and do, if still in my view, maybe a partial view "NoReportAvailablePartial" in case of 0 reports.

which one is better, or how do you solve this scenario?

+2


source to share


3 answers


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

  • If you find that your views start to contain a lot of if / else logic, then they should probably be refactored into separate views and logic hosted in the controller.

  • If your view contains no other repeatable HTML other than if logic (ie list or "no report"), then I would split into 2 views and put the logic in a controller. For example. If you are using master pages containing the rest of the HTML. I think this makes it clearer.

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



I believe that the basic display logic (eg if (report.Count> 0) {}) is fine, but you should stick to the DRY principle and your view should not be cluttered with code.

+4


source


Remember what each part of the MVC pattern should be responsible for; The views should only display the material, while the Controller should decide what to show.



I would choose two different views - one will be responsible for providing the list of items and one will be responsible for providing the error message. These are two completely different things, and the Controller must decide what to do, not the presentation.

+3


source


I prefer a single view if the logic inside is mainly about hiding shared sections.

If there are, however, big differences, such as additional information or controls for users in different roles, then it might be a good idea to organize specific views so that they don't appear.

+2


source







All Articles