Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc 5 SelectList from table with blank value for DropDownList

Use one of the overloads that accepts an optionLabel

@Html.DropDownListFor(m => m.ID, (SelectList)ViewBag.MyList, "Please select", new { @class = "form-control" })

or if you do not want to use the strongly typed methods

@Html.DropDownList("ID", (SelectList)ViewBag.MyList, "Please select", new { @class = "form-control" })

Which will add the first option with the text specified in the 3rd parameter and with a null value

<option value="">Please Select</option>

You can use this overload:

public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes);

where optionLabel is the text for a default empty item.


In my project, these work:

Controller

ViewBag.TagHfoFlagId= new SelectList(db.TableName.OrderBy(x => x.Name),"Id","Name")

View

 @Html.DropDownList("TagHfoFlagId", null,"--Select Name--", htmlAttributes: new { @id = "tags" })

The accepted answer does work, but it will show the default (null) value in the view's drop down list even if you already selected one before. If you want the already selected value to show itself in the drop down list once you render back the view, use this instead :

Controller

ViewBag.Fk_Id_Parent_Table = new SelectList(db.Parent_Table, "Id", "Name", Child_Table.Fk_Id_Parent_Table);
return View(ChildTable);

View

@Html.DropDownList(
             "Fk_Id_Parent_Table",
             null, 
             "Not Assigned", 
             htmlAttributes: new { @class = "form-control" }
                  )