Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding empty string to selectList as SelectedValue

Tags:

c#

asp.net-mvc

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>

like image 780
szpic Avatar asked Apr 16 '26 14:04

szpic


1 Answers

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 = "" });
like image 56
alexmac Avatar answered Apr 19 '26 01:04

alexmac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!