Looping through a list inside a HTML.DropDownList C# MVC - c#

I have been trying to loop through a list inside of a drop down list but it doesn't seem to be working. Here's the code.
public class AnimalHandler
{
public List<string> DogBreeds = new List<string>()
{
"Affenpinscher","Lhasa Apso","Shitzu", "Tibetan Terrier"
}
}
And then in the view
Project1.Models.AnimalHandler animal = new Project1.Models.AnimalHandler();
#Html.DropDownList("breed", new List<SelectListItem> {
foreach(var item in animal.DogBreeds)
{
new SelectListItem {Text="item", Value=""},
}
new SelectListItem {Text="Choose a Breed", Value=""}
})
My thought behind it would be that var item would loop through all the items in the DogBreeds however there seems to be an error and I can't figure out what it could be.
Perhaps there is another SIMPLE way of doing this? Thanks

Something like this:
#Html.DropDownList("breed", new SelectList(animal.DogBreeds), "Choose a breed")
From comments, to set a selected value:
#Html.DropDownList("breed", new SelectList(animal.DogBreeds,
"Great Dane"),
"Choose a breed")
Where you get your selected value from is down to you.

What about something like:
#Html.DropDownList(
"breed",
animal.DogBreeds.Select(x => new SelectListItem { Text = x, Value = x }),
"Choose a Breed")

Related

Create selectlist with groups

I want to create selectlist with items from database grouped by RoomId.
var beds = service.GetApartmentBed(parentId)
.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = localizerBedsType[x.BedType.ToString()],
Group = new SelectListGroup { Name = x.RoomId.ToString()},
}).ToList();
AvailableBeds = new SelectList(beds,
nameof(SelectListItem.Value),
nameof(SelectListItem.Text),
BedId,
nameof(SelectListItem.Group.Name));
But when i want to test it in browser, its shows this error:
Image
This is value of item:
Image
but when i remove last parametr of AvailableBeds it's work well but I don't have groups.
Ok, ive done it. Ive need to change last line to "Group.Name"
AvailableBeds = new SelectList(beds,
nameof(SelectListItem.Value),
nameof(SelectListItem.Text),
BedId,
"Group.Name");

c# how to add a select list items in viewbag

ViewBag.Company= new SelectList(db.i_Company(null).OrderBy(c => c.CompanyName), "CompanyID", "CompanyName");
This ViewBag contains CompanyID, and CompanyName, but I would like to add an additional line for the default selection. I would like to add something like:
CompanyID = 0 and CompanyName= "All Companies"
to the list I have.
How can I add a line manually to this ViewBag?
You first need to create instance of SelectList separately and then insert a new item to 0 the position in it and then assign it to the ViewBag..
Consider doing following.
List<SelectListItem> items = db.i_Company(null).OrderBy(c => c.CompanyName).Select(o => new SelectListItem { Value = o.CompanyID, Text = o.CompanyName}).ToList();
items.Insert(0, (new SelectListItem { Text = "All Companies", Value = "0" }));
ViewBag.Company = new SelectList(items);

Modify text in items in SelectList

I can't find a way to modify the text in each item on a SelectList to populate a dropdown menu. The values I'm populating the list with are from a database and are encrypted. I want to decrypt each item as it is loaded into the list and replace the encrypted text with the decrypted one.
This is an example of what I thought would work, But I still get the same results in the dropdown menu.
public ActionResult Create()
{
SelectList Types = new SelectList(db.Room_Type, "ID_Room_Type", "Name");
foreach(SelectListItem i in Types)
{
i.Text = Util.Crypt.Decrypt(i.Text);
}
ViewBag.Room_Type = Types;
return View();
}
Is there any permanent way to change and process this text as is being loaded?
I think this should work:
var l = new List<SelectListItem>();
foreach(var i in db.Room_Type)
{
var sli = new SelectListItem();
sli.Value = i.ID_Room_Type;
sli.Text = Util.Crypt.Decrypt(i.Name);
l.Add(sli);
}
SelectList Types = new SelectList(l);

Populating Dropdown using Reflection

I am using MVC4 and what I want to do is use a dropdown connected to my search box to search for the selected property. How would I am stuck on the Text= prop.Name. How could I go through and access all of the properties using this.
My Controller
public ActionResult SearchIndex(string searchString)
{
var selectListItems = new List<SelectListItem>();
var first = db.BloodStored.First();
foreach(var item in first.GetType().GetProperties())
{
selectListItems.Add(new SelectListItem(){ Text = item.Name, Value = selectListItems.Count.ToString()});
}
IEnumerable<SelectListItem> enumSelectList = selectListItems;
ViewBag.SearchFields = enumSelectList;
var bloodSearch = from m in db.BloodStored
select m;
if (!String.IsNullOrEmpty(searchString))
{
bloodSearch = bloodSearch.Where(s => string.Compare(GetValue(s, propertyName), searchString) == 0);
}
return View(bloodSearch);
}
The selectlist is working now I just need to go over my searchstring and how to pass two parameters now.
I'm not quite sure what you're asking. If you want to create a list of objects with the property Text set to the property name of the object, you could get the first object in the BloodStored enumerable and create a list of anonymous types:
// Get one instance and then iterate all the properties
var selectListItems = new List<object>();
var first = db.BloodStore.First();
foreach(var item in first.GetType().GetProperties()){
selectListItems.Add(new (){ Text = item.Name});
}
ViewBag.SearchFields = selectListItems;

SelectList Not Coming Back Sorted - C# MVC 3

All,
I am trying to sort my selectlist items and then prepend a default list item to the list, something like "Select an Item Below" and return that list via a method. I noticed that the list is not being sorted because it looks like, from what ReSharper is saying, I need to return the sorted result - so my method is not returning a sorted list.
Is there a way to do the sorting and prepending in the method?
Here is what I have:
public static IEnumerable<SelectListItem> GetBuildingClubs(List<BuildingClub> localClubs, List<BuildingClub> psfyClubs)
{
var buildingClubList = new List<SelectListItem>();
IEnumerable<BuildingClub> allBuildingClubs = localClubs.Union(psfyClubs);
foreach (BuildingClub b in allBuildingClubs)
{
buildingClubList.Add(new SelectListItem
{
Value = b.MasterCustomerId,
Text = b.NewBuildingClubName
});
}
//Sort list
buildingClubList.OrderBy(c => c.Text);
//Prepend to sorted list
buildingClubList.Insert(0, new SelectListItem
{
Value = "",
Text = "Select an Item Below"
});
return buildingClubList;
}
OrderBy doesn't modify the input list; it returns a new sorted sequence. You need to store that sequence and use it to build your list:
buildingClubList = buildingClubList.OrderBy(c => c.Text).ToList();
Alternatively, sort the items before you add them to the list:
IEnumerable<BuildingClub> allBuildingClubs = localClubs.Union(psfyClubs).OrderBy(b => b.NewBuildingClubName);

Categories

Resources