21

I have the following code that is in my formViewModel to be passed to my View.

        var ownerValues = aspnet_Users
            .OrderBy(u => u.Surname)
            .Select(u => new KeyValuePair<int, string>(u.UserId, u.Surname + " " + u.Forename.ToString() + " [" + u.UserName.ToString() + "]"));
        this.OwnersList = new SelectList(ownerValues, "Key", "Value", incidentAction.OwnerId);

When I run the view in explorer my drop list defaults to the first item and I want it to default to a blank row.

So my plan is to insert a initial row with userId = null and then an empty string instead of 'please select' or something similar.

Can anyone please advise me on how to do this on one line of code I think, not sure where to start.

thanks

John
  • 1,459
  • 4
  • 21
  • 45

3 Answers3

33

When Rendering your SelectList you can do something like

<%:Html.DropDownListFor(x => x.ApprovalType, Model.ApprovalTypes,"")%>

if you want strongly typed list or you can try

<%:Html.DropDownList("ApprovalType", Model.ApprovalTypes, "") %>

in both examples Model.ApprovalTypes contains a SelectList or List of SelectListItems. Empty string parameter at the end is optional label and its value is also an empty string
Edit Inserting label (empty string or something else) with some value will also create problems when you try to validate it using data annotations. Selecting empty label will not trigger the error message because associate value will be -1 (not empty) as suggested in other answer.

Muhammad Adeel Zahid
  • 17,474
  • 14
  • 90
  • 155
8

userid cannot be null (since it's int) but if -1 works, you can try

 this.OwnersList = new SelectList(new[]{new KeyValuePair<int, string>(-1, "please select")}.Union(ownerValues), "Key", "Value", incidentAction.OwnerId);
Bala R
  • 107,317
  • 23
  • 199
  • 210
4

Create your own List<SelectListItem> and then do an Insert


List<SelectListItem> MyOwnerList = new List<SelectListItem>();
MyOwnerList.AddRange(new SelectList(ownerValues, "Key", "Value", incidentAction.OwnerId);
MyOwnerList.Insert(0, new SelectListItem{Text = "", Value = ""});
this.OwnersList =MyOwnerList;