Removing logic from partial views in ASP.NET MVC

I know that there shouldn't be code in the views, but in the project I'm working on, I have a lot of logic in the views.

My homepage has

<% Html.RenderPartial("SearchResults"); %> 

Now in a partial view, I have quite a bit of logic, for example:

 <div id="RestaurantsList"> <%if (Model.restaurantsList.Count() > 0) { foreach (var item in Model.restaurantsList) { %> <% Html.RenderPartial("SearchResult", item); %> <% } %> <% } else { Html.RenderPartial("NoResults"); } %> 

Now I can make the home controller return another view based on the empty blank, but I really don't want this, because there are several things in the Index view that I want to display, regardless of whether there are any results or not.

The only thing I can think of here is encapsualte this in a helper method like Html.SearchResults. But then I need an assistant to call renderPartial for each search result. This is not like a clean separation of concerns.

I would still have to have an if if statement in a partial view.

How would you do better?

+7
asp.net-mvc refactoring partial-views
source share
4 answers

My personal opinion is that everything is in order. The logic you used is completely related to how the model should be displayed.

You just need to know and make sure that you never mix business logic, data access logic, or anything else that is not related to model rendering.

+13
source share

I agree with the answer of Praven Angyan. The only thing I can say to extend his answer is to put some of the logic in the ViewModel.

For example, in ViewModel you can hide

Model.restaurantsList.Count() > 0

for a method or property.

eg:.

 <%if (Model.HasResturant){...}%> 
+10
source share

This answer has nothing to do with your question.

However, I just want to tell you that calling html.RenderPartial () inside the loop is inefficient .
ASP.NET MVC - for a loop inside a RenderPartial or an external RenderPartial

It would be better to change it to something like below.

 <%if (Model.restaurantsList.Count() > 0) { // render the Restaurant item right away foreach (var item in Model.restaurantsList) { %> <div> <%= Html.Encode(item.RestaurantName); %><br /> <%= Html.Encode(item.Address); %> </div> <% } } else { Html.RenderPartial("NoResults"); } %> 
+1
source share

Pravain Angyan is right - this is the logic of views, and it is wonderful that it is somewhere. But this does not change the need for more sophisticated looks.

Just wanted to share a little improvement.
If we apply the tiny HtmlHelper method, we can shorten the view to something like this:

 <div id="RestaurantsList"> <% if (Model.HasRestaurants) Html.RenderPartialForEach("SearchResult", Model.restaurantsList); else Html.RenderPartial("NoResults"); %> </div> 

For some, it may seem unreadable and enjoyable, but it suits me well enough.

+1
source share

All Articles