What a difference between Dropdownlistfor and Dropdownlist

Asked

Viewed 1,799 times

6

What a difference between Dropdownlistfor and Dropdownlist?

And when and which to use?

3 answers

8


Dropdownlist

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

Dropdownlistfor

  • Heavily typed (Compile time)
  • Implemented in MVC 2
  • Supports lambda expressions.
  • Just specify the data type and source via Viewmodel.

7

Complementing the @Laerte response:

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

@Html.DropDownList("MeuUnicoCampoInteiro", MinhaVariavelSelectList)

To Action of Controller could be made just like this:

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

Already the DropDownListFor is the best option for Models and ViewModels, whereas the first argument is strongly typed, i.e., the parameter needs to exist in the Model or ViewModel in question.

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

@Html.DropDownListFor(model => model.MinhaClassePai.MinhaClasseAninhada.MinhaPropertyInteira, MinhaVariavelSelectList, "Escolha uma opção...")

4

Let’s take two examples:

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

and:

@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 if you decide to refactor your model and rename this property, to support tool you should be using will not have any how to detect this change and automatically modify the string that you typed in probably many views. So you have to, manually, search and replace wherever used this weakly typed helper.

With the first example, on the other hand, we’re using a strongly typed lambda expression tying to model property provided and then tools will be able to rename automatically everywhere it is used if you decide refactor your code. Also if you decide to precomp your views you will receive an error at build time 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 execution time when they visit this particular view.

Heavily 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.