Modify text in items in SelectList - c#

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);

Related

Invalid Operation Exception passing to View

I am trying, to no avail to display a dropdown list of all units a user doesnt already have. So i have List A with all Units and List B with all Units the user has. What i want is List C which is basically List A with List B removed from it. I have so far managed to filter out the data but i cant seem to display it in my View. All i get is a blank dropdown list. Can anyone see where im going wrong??
public ActionResult AddUnit(String usrCode)
{
var units = unitsClient.GetAllunits();
var allunitsCode = (from s in units select s.unitCode).ToList();
var thisUnitCode = (from s in db.Units
where s.UsrCode == usrCode
select s.UnitCode).ToList();
var notGot = allunitsCode.Except(thisUnitCode);
List<unitsummaryDTO> list = UnitList(units, notGot);
ViewBag.unitCode = new SelectList(list, "unitCode", "unitTitle");
var model = new UserUnit { UsrCode = usrCode };
return View("AddUnit", model);
}
private List<unitsummaryDTO> UnitList(unitsService.unitsDTO[] units, IEnumerable<string> notGot)
{
var allunits = unitsClient.GetAllunits();
var allunitsCode = (from s in allunits select s.unitCode).ToList();
IEnumerable<String> list1 = allunitsCode;
IEnumerable<String> list2 = notGot;
var listFinal = list1.Union(list2).toList;
return listFinal.Select(x => new unitsummaryDTO(){unitCode = x}).ToList();
}
This is my View model. But all i get is a blank drop down?? Can anyone help me out.
#model Projv1.UserUnit
#Html.HiddenFor(model => model.unitCode)
#Html.DropDownList("UnitCode")
It would be blank because #Html.DropDownList("UnitCode") doesn't have a source. If you look at MSDN for Html.DropDownList, the one your most likely trying to use is DropDownList(String, IEnumerable<SelectListItem>).
Your putting your select list into the ViewBag as unitCode so try:
#Html.DropDownList("Unit Code", ViewBag.unitCode);
A much easier way of handling this is to extend UserUnit as a ViewModel (or create something) to have the items needed by the SelectList on it and let MVC do the heavy lifting in the binding.
public class UserUnit
{
// ... other properties
IEnumerable<unitsummaryDTO> UnitCodes { get; set; }
public string MyUnitCode { get; set; }
}
Then
#Html.DropDownListFor(n => n.MyUnitCode,
new SelectList(Model.UnitCodes, "unitCode", "unitTitle"))

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

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")

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);

Setting selected values on MultiSelectList C#

I'm working with a simple MultiSelectList on C#.
I just want to populate this MultiSelectList with some string values (not a pair such as <"Key", "Value"> just <"Value">) and set some selected items.
Here's my code:
IEnumerable<string> ubicaciones = new string[] { "NEGOCIOS", "TERRITORIOS",
"LOCALIDADES" };
IEnumerable<string> ubicacionesSelected = Ubicaciones.Split(',');
UbicacionesPermitidas = new MultiSelectList(ubicaciones, ubicacionesSelected);
IEnumerable<string> transacciones = new string[] { "CARGA: ACCESORIOS",
"CARGA: EQUIPOS", "ASIGNACIONES", "DESINCORPORACIONES",
"PRÉSTAMOS", "TRASLADOS", "SALIDAS" };
IEnumerable<string> transaccionesSelected = Transacciones.Split(',');
TransaccionesPermitidas = new MultiSelectList(transacciones,
transaccionesSelected);
However, is not working... (it shows all the values on the MultiSelectList but it doesn't show any item selected) what am I missing?
Thanks.
The values in Ubicaciones do not match up with the values in ubicaciones. It's the same with Transacciones and transacciones. If you don't believe that that's the case, please post the code which defines Ubicaciones and Transacciones and we can troubleshoot it further.

Categories

Resources