Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing logic from partial views in ASP.NET MVC

I am aware that views should not have code in them but in a project I am working on I have a lot of logic in the views.

My home page has

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

Now in the partial view I have an aweful lot of logic like this;

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

    <%
    } %>
<%
}
else
{
    Html.RenderPartial("NoResults");

} %>

Now I could make the home controller return a different view based on the list being empty but I don't really want that as the Index view has a few things that I want displayed no matter if there are results or not.

The only other thing I can think of here is to encapsualte this in a helper method like Html.SearchResults. But then I would need the helper to call the renderPartial for each search result also. That doesn't seem like clean seperation of concerns.

I would still have to have the first if statement in the partial view though.

How would you best handle this?

like image 453
ddd Avatar asked Jun 05 '09 16:06

ddd


People also ask

Can we return partial view in MVC?

In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.

How do you render a partial view inside a view in MVC?

Partial function which renders the Partial View. The name of the View and the object of the CustomerModel class are passed to the @Html. Partial function. In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.

Can partial view have controller?

It does not require to have a controller action method to call it. Partial view data is dependent of parent model. Caching is not possible as it is tightly bound with parent view (controller action method) and parent's model.


1 Answers

My personal opinion is that this is okay. The logic that you've used is totally related to how the model needs to be displayed.

You just need to be aware and make sure that you're never mixing in business logic, data access logic or anything else that isn't strictly tied in to the display of the model.

like image 136
Praveen Angyan Avatar answered Nov 11 '22 16:11

Praveen Angyan