简体   繁体   中英

C# DropDown List default value

I am using this code to input values from a database table to a dropdown list:

<div class="editor-field">
        @Html.DropDownListFor(model => model.TourImageID, new SelectList(Model.Images, "ImageID", "Filename", Model.TourImageID))
</div>

What i am trying to do is add an item to the top of the list, that is not present in the database table.

Something like DROPDOWN LIST VALUES = (DEFAULT-ITEM) + (DATABASE-TABLE-ITEMS)

is that possible? if so, how?

If your Model.Images is of type SelectList , you can do something like this in your controller:

var query = UnitOfWork.GlobalImageLibraryRepository.Images.Select(x => new { x.ImageID, x.Filename });

viewModel.Images = new SelectList(query.AsEnumerable(), "ImageID", "Filename");
viewModel.Images.Insert(0, new SelectListItem { Value = "0", Text = "--Select--" });

I've assumed that you have a method in your GlobalImageLibraryRepository class that returns IQueryable<Images> like this:

public IQueryable<Images> Images { get { return dbcontext.Images; } }

So after all that, your view will look like this:

<div class="editor-field">
        @Html.DropDownListFor(model => model.TourImageID, (SelectList)Model.Images, Model.TourImageID))
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM