0

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")
MethodMan
  • 18,625
  • 6
  • 34
  • 52
bilpor
  • 3,467
  • 6
  • 32
  • 77

2 Answers2

0

You should add a simple value type property to your view model to hold the selected value.

public class YourViewModel
{
  IEnumerable<SelectListItem> beneficiaryNames  { set;get;}
  public int? BeneficiaryId { set;get;}
}

Now in your view, use this new property in DropDownListFor helper method.

@model YourViewModel
@Html.DropDownListFor(s=>s.BeneficiaryId,Model.beneficiaryNames,"None selected")

To select an item, set the BeneficiaryId value of your view model in your GET action. Assuming beneficiaryNames is a collection of Items with Id and Name property,

public ActionResult Edit(int id)
{
  var vm = new YourViewModel();
  vm.beneficiaryNames= beneficiaryNames.Select(s=>new SelectListItem {
                            Value=s.Id.ToString(),
                            Text=s.Name }).ToList();
  vm.BeneficiaryId=2; // Will select the option with value 2, (Record with Id 2)
  return View(vm);
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
0

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

bilpor
  • 3,467
  • 6
  • 32
  • 77