What difference between DropDownListFor and DropDownList

6

What is the difference between DropDownListFor and DropDownList?

And when and which one to use?

    
asked by Jota 11.02.2015 в 13:20
source

3 answers

8

DropdownList

  • Weakly typed (Run-time checking)
  • Implemented in MVC 1
  • Does not support lambda expressions.
  • Need to specify ID / Element name.

DropDownListFor

  • Strongly typed (Compile time)
  • Implemented in MVC 2
  • Supports lambda expressions.
  • Just specify the type and data source via ViewModel.
answered by 11.02.2015 / 13:37
source
7

Complementing @Laerte's answer:

The DropDownList can be used for elements outside Model , such as in case the programmer does not want to implement a ViewModel because it needs only one field of form :

@Html.DropDownList("MeuUnicoCampoInteiro", MinhaVariavelSelectList)

The Action of Controller could be done simply like this:

public ActionResult MinhaAction(int MeuUnicoCampoInteiro) { ... }

Since DropDownListFor is the best option for Models and ViewModels , considering that the first argument is strongly typed, ie the parameter must exist in Model or ViewModel .

DropDownListFor is also the most appropriate option when class nesting. For example:

@Html.DropDownListFor(model => model.MinhaClassePai.MinhaClasseAninhada.MinhaPropertyInteira, MinhaVariavelSelectList, "Escolha uma opção...")
    
answered by 11.02.2015 в 13:51
4

Let's take two examples:

@Html.DropDownListFor(
    x => x.EquipamentoId, 
    new SelectList(Model.Equipamentos, "Id", "Text")
)

e:

@Html.DropDownList(
    "EquipamentoId", 
    new SelectList(Model.Equipamentos, "Id", "Text")
)
  

It is obvious that in the second example the name of the property you are   linking to the dropdown is typed as a string. This means that   you decide to refactor your model and rename this property, the   tool you should be using will not have any   way to detect this change and automatically modify the string   which you typed in probably many views. So you have to,   manually, search and replace wherever it is used   this weakly typed helper.

     

With the first example, on the other hand, we are using a   strongly typed lambda expression tying to the model property   provided and then tools will be able to rename   anywhere you use it if you decide   refactor your code. Also if you decide to precompile your views   you will receive a compile-time error immediately pointing   for the view that needs to be corrected. With the second example you   (ideal case) or users of your site (worst case) will receive an error in   time when they visit this particular view.

     

Strongly typed helpers were introduced in ASP.NET MVC 2 and the   last time I used a weakly typed type was in an application   in ASP.NET MVC 1 a long time ago.

Originally translated from this link

    
answered by 11.02.2015 в 14:02