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>

2
  • 2
    possible duplicate of MVC - Clear default selected value of SelectList Commented Mar 4, 2014 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 Commented Mar 4, 2014 at 12:34

1 Answer 1

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 = "" });
Sign up to request clarification or add additional context in comments.

2 Comments

Look promising. Now I only need to find how to insert something into my IEnumerable items collection
Just convert it ToList, and call Insert.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.