bilpor bilpor - 2 months ago 5
C# Question

I cannot set default value on dropdownlistfor

I have a constructor that passes in an IEnumerable of an object and then expose it from a public variable of type SelectList. In the cshtml file It has been mapped to a DropDownListFor and the dropdown populates fine, However when I try to attach "None selected" to the dropdown it doesn't display in the screen e.g.

constructor of the view model:

IEnumerable<Partner> beneficiaryNames

setting the value in the constructor:

BeneficiaryNames = new SelectList(beneficiaryNames, "Id", "Name");

declaration in viewmodel:

public SelectList BeneficiaryNames { get; set; }

then in my view:

@Html.DropDownListFor(m => m.SearchRequest.BeneficiaryId, Model.BeneficiaryNames, "None selected")


in the constructor of the view model I had to force a new object into the list. so I had to replace BeneficiaryNames = new SelectList(beneficiaryNames, "Id", "Name"); with List<Partner> newList = new List<Partner>() { new Partner { Id = 0, Name = "None Selected" } }; newList.AddRange(beneficiaryNames); BeneficiaryNames = new SelectList(newList, "Id", "Name");