Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - How best to organize commonly used drop-down lists in many views

I am trying to understand how best to organize some common Dropdown lists used in several views (some are cascading)

Is it best to create a single \Models\CommonQueries then create a webservice for each dropdown used in cascading situation then have a single controller that contains actions for each dropdowns

This way I can follow DRY principle and not repeat the dropdown logics since they are used in various views.

Much Thanks and Regards for reading my question and taking the your time. +ab

like image 214
ab. Avatar asked Nov 06 '22 17:11

ab.


1 Answers

When you say your dropdowns are used in several views, do you still consider these dropdowns as part of the view that is rendering them? If so, I think using a custom HTML helper or a partial view (ascx) is appropriate. Then, like you suggest, you can populate the data for the dropdowns using a common service from your domain layer. I think that is a very reasonable approach.

However, if you feel the dropdowns are somewhat external/unrelated to the view, then you might find that using Html.RenderAction() gives you a much cleaner result. Using Html.RenderAction(), you can output the result of an Action method directly into any other view. Therefore, you can create 1 controller with the necessary Action method(s) to populate those dropdowns. For example, let say you have a view with roughly something like:

<div>
    <div id="coreView1">
        <!-- some view code here -->
    </div>
</div>

<div id="commonDropdowns">
        <% Html.RenderAction("Create", "Dropdown"); %>
</div>

where Create is the name of your method in the DropdownController.

For example:

public class DropdownController : Controller
{
    public ViewResult Create()
    {
        // do stuff here to create the ViewResult of the common Dropdowns
    }
}

Note: Some people dislike this approach as it doesn't fit the typical MVC seperation of concerns. However, it can be a really great fit for some cases.

Hope one of these approaches can help.

like image 159
Chris Melinn Avatar answered Nov 15 '22 11:11

Chris Melinn