DropDownListFor Helper in MVC3 Razor

  • Html.DropDownList renders a dropdown list.
  • Helpers are not controls by itself, they simply generate html markup.
  • It basically generates select element with options.
  • This helper helps in binding the dropdown with model.

It has following Overloads :


Overload 1 :


This overload accepts a linq expression and a IEnumerable list to bind the control.

Syntax:

<p>
    @Html.DropDownListFor(c => c.Cars, list)
</p>



UI :


Rendered HTML :

<select id="Cars" name="Cars"><option value="lamb">Lamborgini</option>
<option value="merc">Mercedes</option>
<option value="ferr">Ferrari</option>
<option value="bm">BMW</option>
</select>


Overload 2 :




This overload is similar to previous one, this accepts htmlAttributes parameter extra to previous one.

Syntax :

<p>
    @Html.DropDownListFor(c => c.Cars, list, new { style = "color:Red;"})
</p>




UI :




Rendered HTML :

<select id="Cars" name="Cars" style="color:Red;">
<option value="lamb">Lamborgini</option>
<option value="merc">Mercedes</option>
<option value="ferr">Ferrari</option>
<option value="bm">BMW</option>
</select>


Overload 3 :




Syntax :

<p>
    @Html.DropDownListFor(c => c.Cars, list,"Hello World")
</p>

UI :




Rendered HTML :

<select id="Cars" name="Cars">
<option value="">Hello World</option>
<option value="lamb">Lamborgini</option>
<option value="merc">Mercedes</option>
<option value="ferr">Ferrari</option>
<option value="bm">BMW</option>
</select>


Overload 4 :




Syntax :

<p>
    @Html.DropDownListFor(c => c.Cars, list,"Hello World")
</p>

UI :




Rendered HTML :

<select id="Cars" name="Cars">
<option value="">Hello World</option>
<option value="lamb">Lamborgini</option>
<option value="merc">Mercedes</option>
<option value="ferr">Ferrari</option>
<option value="bm">BMW</option>
</select>


Overload 5 :




Syntax :

<p>
    @Html.DropDownListFor(c => c.Cars, list, "Hello World", new { style="color : Red;"})
</p>

UI :




Rendered HTML :

<select id="Cars" name="Cars" style="color : Red;">
<option value="">Hello World</option>
<option value="lamb">Lamborgini</option>
<option value="merc">Mercedes</option>
<option value="ferr">Ferrari</option>
<option value="bm">BMW</option>
</select>


Overload 6 :




Syntax :

<p>
    @Html.DropDownListFor(c => c.Cars, list, "Hello World", DropdownList)
</p>




UI :




Rendered HTML :

<select id="Cars" name="Cars" style="color:Red;width:200px;">
<option value="">Hello World</option>
<option value="lamb">Lamborgini</option>
<option value="merc">Mercedes</option>
<option value="ferr">Ferrari</option>
<option value="bm">BMW</option>
</select>


0 comments:

Post a Comment