Difference between DropDownlist or DropDownListFor Html helper

Take the following two examples:

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

and:

@Html.DropDownList(
    "EquipmentId", 
    new SelectList(Model.Equipments, "Id", "Text")
)

It is obvious that with the second example the name of the property you are binding the dropdown to is hardcoded as a magic string. This means that if you decide to refactor your model and rename this property Tooling support that you might be using has no way of detecting this change and automatically modifying the magic string you hardcoded in potentially many views. So you will have to manually search & replace everywhere this weakly typed helper is used.

With the first example on the other hand we are using a strongly typed lambda expression tied to the given model property so tools are able to automatically rename it everywhere it is used if you decide to refactor your code. Also if you decide to precompile your views you will get a compiler time error immediately pointing to the view that needs to be fixed. With the second example you (ideally) or users of your site (worst case scenario) will get a runtime error when they visit this particular view.

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

Leave a Comment