3

I'm populating DropdownList with data retrieved from database. I want to add default empty string. I'm trying with SelectedValue property with no effects. I tried already null and string.empty like in sample below

ViewBag.Project = new SelectList(unitOfWork.projectRepository.Get(), "ProjectName", "ProjectName",string.Empty);

DropDownList declaration in View

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

which translates into:

<select class="form-control" id="Project" name="Project">
    <option value="Sample project">Sample project</option>
    <option value="Second project">Second project</option>
</select>

By there is no option with String.Empty.

What should I change in my code

As @Alexander suggested I converted it with ToList and now this is my code:

var items = unitOfWork.projectRepository.Get();
items=items.ToList<Project>().Insert(0, new Project { ProjectId = 1, ProjectName = "" });
ViewBag.Project = new SelectList(items, "ProjectName", "ProjectName",string.Empty);

but this throws exception:Error Cannot implicitly convert type 'void' to 'System.Collections.Generic.IEnumerable<magazyn.Models.Project>

szpic
  • 4,346
  • 15
  • 54
  • 85
  • 2
    possible duplicate of [MVC - Clear default selected value of SelectList](http://stackoverflow.com/questions/3780614/mvc-clear-default-selected-value-of-selectlist) – Andrei Mar 04 '14 at 12:19
  • 1
    In the amendment, break your second line of code into two; you're trying to assign the result of Insert() to items - Insert() doesn't return a value (is void). Do the ToList on the same line as the Get to change the type of items at declaration – Dave Mar 04 '14 at 12:34

1 Answers1

5

SelectList contains no overloads that accept an empty default option. You can add it to your items collection manually:

var items = unitOfWork.projectRepository.Get();
items.Insert(0, new Item {ProjectId = null, ProjectName == "", });

ViewBag.Project = new SelectList(items, "ProjectName", "ProjectName",string.Empty);

Update

About the additional convert exception: You are trying to assign the result of the Insert function to a List. Use this code:

var items = unitOfWork.projectRepository.Get().ToList();
items.Insert(0, new Project { ProjectId = 1, ProjectName = "" });
ruffin
  • 16,507
  • 9
  • 88
  • 138
alexmac
  • 19,087
  • 7
  • 58
  • 69