MVC - How best to organize commonly used drop-down lists in many views
I am trying to understand how best to organize some common Dropd开发者_JS百科own 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
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.
精彩评论