Best practice MVC4 for DropDownListFor listing from a database or code

I am new to MVC and wondered what is the best way to populate a dropdown in editor templates?

I am creating an application with a lot of dropdown menus and the data for these dropdowns is very static. I currently have all of them in a table in db, and then load them into the session.

Here is an example:

My opinion:

@{ var widgettypes = Business.MySession.Current.WidgetTypes.ToSelectList(d => d.TypeName, d => d.WidgetTypeID.ToString(), " - Select - "); } <div class="editor-label"> @Html.LabelFor(model => model.WidgetTypeID) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.WidgetTypeID, @widgettypes) @Html.ValidationMessageFor(model => model.WidgetTypeID) </div> 

Dropdown Folder Assistant:

  public static List<SelectListItem> ToSelectList<T>( this IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value, string defaultOption) { var items = enumerable.Select(f => new SelectListItem() { Text = text(f), Value = value(f) }).ToList(); items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" }); return items; } 

I saw many examples here on SO that show creating a picklist in a view statically.

Is it better to create them in a view from a static enum in .net code, or is it best to do it the way I do it now? Or is it just not important?

I just want to know what I should do, not what just works.

+4
source share
1 answer

I personally believe that database management is the way to go. Mostly from experience, let's say you wanted to add a value to your search, and you have already deployed your application, you will have to redeploy the code after adding a new value to Enum. Due to the fact that they are managed by the database, you can simply run the insert request to the database, and redeployment is not required.

I would not call your database in your view like this, although I would not say that this is the best practice, since it is not the responsibility to browse, it just needs to display the data, and not request additional data.

First of all, place your items in your drop-down list in your model, for example:

 public class YourModel { public int WidgetTypeId { get; set; } public SelectList WidgetTypes { get; set; } //...rest of your model } 

Then, in your GET method in your controller (before returning your view, fill this list with the code that you have in the view:

 public ActionResult MyAction() { YourModel model = new YourModel(); model.WidgetTypes = Business.MySession.Current.WidgetTypes .ToSelectList(d => d.TypeName, d => d.WidgetTypeID.ToString(), " - Select - "); return View(model); } 

Then, in your opinion, just do:

 @Html.DropDownListFor(model => model.WidgetTypeID, Model.WidgetTypes) 
+6
source

All Articles