mvc 5 SelectList from table with blank value for D

2019-01-18 03:20发布

问题:

I am using below code to create a drop down

Controller

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

View

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

My question is how can I Modify SelectList to add a blank item so that there is a blank item automatically added for DropDownList.

Thanks.

回答1:

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>


回答2:

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.



回答3:

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" })


回答4:

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" }
                  )