Get contents of enum to a dropdownlist - c#

I am trying to convert my Items from Enum to a dropdownlist .Please help
public enum Colors{ red,blue,green,yellow,orange,white,black,Teal,Custom }
#Html.DropDownList("SelectedColourId", Model.ColourList, "(Select one Color)")
My ViewModel is below
myPageViewModel:BasicViewModel
{
.....
public IEnumerable<SelectListItem> ColourList{ get; set; }
.........
}
I am tried something like
myViewModel.ColourList = Enum.GetNames(typeof(Colors)).ToArray()
.Select(e => new SelectListItem() { Text = e.item, Value = e.itemindex });
But I don't know how to get itemText and its correesponding Index .Its throwing errors

In the controller, initialize the ColourList array using the Enum GetNames static method and Linq:
myPageViewModel.ColourList = Enum.GetNames(typeof(Colors))
.Select(c => new SelectListItem() { Text = c, Value = c })
.ToArray();

to add the option in dropdown from enum use the below code:
foreach (DropDownEnum enumValue in Enum.GetValues(typeof(DropDownEnum)))
{
model.SortOptions.Add(new SelectListItem()
{
Text = enumValue.ToString(),
Value = url+enumValue.ToString(),
Selected = false
});
}

Related

.NET 6 - Set SelectListItem to Selected?

I have a DropDownList which I populate like below:
Controller
IEnumerable<Category> categories = _db.Category.ToList();
var selectList = _db.Category.Select(i => new SelectListItem()
{
Text = i.Name,
Value = i.Id.ToString()
});
ViewBag.categoriesSelectList = selectList;
And use in view like so:
<select asp-for="Category" name="categoryID" asp-items="#ViewBag.categoriesSelectList" class="form-control">
<option>Vælg Kategori:</option>
</select>
However, I can't seem to figure out how I can set the already selected value, so the dropdown "starts" on that value. I tried enumerating over the selectList and changing the Selected attribute of the SelectListItem, but it doesn't work since it won't save the changes I make.
Hope my question makes sense :) thanks all.
Option 1:
Modify your code to include Selected property when creating list of SelectListItem items:
var selectList = _db.Category.Select(i => new SelectListItem()
{
Text = i.Name,
Value = i.Id.ToString(),
Selected = /* Some condition that is true when the current item should be selected */
});
Option 2:
Define a view model with structure that might be referenced in the <select> tag:
public class SelectViewModel
{
public string Category { get; set; }
public List<SelectListItem> Categories { get; set; }
}
The action method:
public IActionResult Categories()
{
var model = new SelectViewModel() ;
model.Categories = _db.Category.Select(i => new SelectListItem()
{
Text = i.Name,
Value = i.Id.ToString()
});
model.Category = ... your_code_to_set_default_selection;
return View(model);
}
The view:
#model SelectViewModel
<select asp-for="Category" asp-items="#Model.Categories"></select>
Can find some mode information in the documentation: The Select Tag Helper

DropDownListFor not selecting with decimal values

I'm working with ASP.NET MVC 5 and Entity Framework 6, and I'm having a problem with the model selected value (only for decimal values) in my views.
That only happen when i'm getting data from database, if i try to submit the form, the value get back and is correctly selected.
This is my ViewModel
public class Regulacion
{
public IEnumerable<SelectListItem> ListaPorcentajePuntos
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text="0,625%" , Value = "0,625"},
new SelectListItem { Text="1%" , Value = "1"},
new SelectListItem { Text="1,25%", Value="1,25" },
new SelectListItem { Text="2,5%" , Value = "2,5"},
new SelectListItem { Text="5%" , Value = "5"},
};
}
}
public decimal? PorcentajePunto { get; set; }
//other stuff
public Regulacion(Reg reg)
{
PorcentajePunto = reg.PorcentajePunto;
}
}
And i'm using it in the view like this
#Html.DropDownListFor(x => x.PorcentajePunto, Model.ListaPorcentajePuntos, "Please select", new { #class = "form-control"})
I'm pretty sure, the problem become when i fetch the data from EF and decimal precision, because, when I'm debugging, the PorcentajePunto property stored 5.00 instead of 5, if i manually modify the property to 5 it works perfectly.
I read this question and try to use SelectList instead of SelectListItem but wasn't the solution
How can i deal with it?
Thanks!
EDIT
I'm fetching the Regulacion data like this
using(var db = new DBTrafosContext())
{
var a = db.Reg.FirstOrDefault();
if(a != null){
Regulacion newRegulacion = new Regulacion(a);
}
}

ASP.NET MVC 4 - DropDown selected value doesn't work

In my ViewModel i got two fields :
public AdTypeEnum Type { get; set; }
public IList<SelectListItem> TypeEnumList { get; set; }
That's how i fill the list :
public void SetLists()
{
TypeEnumList = new List<SelectListItem>();
TypeEnumList.Add(new SelectListItem { Value = "0", Text = "Select the type"});
foreach (var en in Enum.GetValues(typeof(AdTypeEnum)).Cast<AdTypeEnum>())
{
TypeEnumList.Add(new SelectListItem
{
Value = ((int)en).ToString(),
Text = en.ToString(),
Selected = Type == (AdTypeEnum)en ? true : false
});
}
}
And then I'm just rendering a dropdown on my View :
#Html.DropDownListFor(x => x.Type, Model.TypeEnumList, new { #class = "form-control" })
But the selected value doesn't render and the first option is always selected. When I check the select in HTML I found that no one of the options got selected attribute, but when I debug my controller method I can see that always one of the selectListItem have the propety Selected=true. Why does it suddenly disappear when my view is rendering?
Ok I already found out the result. I just had to change the Type from Enum into int and correctly populate it. Everything works! :)

mvc 4 drop down default value selected

I want to select the default value in drop down list where policyId = 7 but it didn't select that value, what i am doing wrong?
Controller:
var pm = new ManagerClass();
IEnumerable<myClass> po = pm.GetDataFromDb();
IEnumerable<SelectListItem> Policies = new SelectList(po, "PolicyID", "PolicyName", new { PolicyID = 7 });
ViewBag.Policies = Policies;
View:
#Html.DropDownListFor(m => m.PolicyID, ViewBag.Policies as IEnumerable<SelectListItem>, new { #class = "dropdown-field"})
It's because it's not actually selecting the value in the SelectList.
First, to make it nicer, put the items in your view model to prevent the cast (this is better practice too):
public class MyModel
{
public int PolicyID { get; set; }
public List<SelectListItem> Policies { get; set; }
//rest of your model
}
Then populate it:
var model = new MyModel();
model.Policies = po
.Select(p => new SelectListItem
{
Text = p.PolicyName,
Value = p.PolicyID.ToString(),
Selected = p.PolicyID == currentPolicyId //change that to whatever current is
})
.ToList();
Then in your view, do:
#Html.DropDownListFor(m => m.PolicyID, Model.Policies, new { #class = "dropdown-field"})
Just set the PolicyID property on your view model to the value you want to be preselected:
var pm = new ManagerClass();
var po = pm.GetDataFromDb();
ViewBag.Policies = new SelectList(po, "PolicyID", "PolicyName");
viewModel.PolicyID = 7;
return View(viewModel);
Since your DropDownList is bound to the PolicyID property (m => m.PolicyID), then its value will be used when deciding which element to be preselected.
In case that you have a static menu:
1- create the following class:
public static class StaticMenus
{
public static List<string> GetGridRowsCount()
{
List<string> result = new List<string>();
result.Add("3");
result.Add("5");
result.Add("10");
result.Add("20");
result.Add("25");
result.Add("50");
result.Add("100");
return result;
}
}
2- add the following code to your controller :
ViewData["CountryList"] = new SelectList(StaticMenus.GetGridRowsCount(),"10");
3- add the following code to your view:
#Html.DropDownList("MainGridRowsCount", ViewData["RowsCountList"] as SelectList)

Set selected value in dropdown list

How do I set the selected value on a drop down list? Here is what I have so far:
#model Web.Models.PostGraduateModels.PlannedSpecialty
#Html.DropDownList("PlannedSpecialtyID")
//controller
[HttpGet]
public PartialViewResult PlannedSpecialty()
{
// Get Planned Specialty ID
var pgtservice = new PgtService();
PostGraduateModels.PlannedSpecialty plannedSpecialty = pgtservice.GetPlannedSpecialtyId();
// Get Data for Planned Specialty DropDown List from SpecialtyLookup
var pgtServ = new PgtService();
var items = pgtServ.GetPlannedSpecialtyDropDownItems();
ViewBag.PlannedSpecialtyId = items;
return PartialView(plannedSpecialty);
}
// service
public IEnumerable<SelectListItem> GetPlannedSpecialtyDropDownItems ()
{
using (var db = Step3Provider.CreateInstance())
{
var specialtyList = db.GetPlannedSpecialtyDdlItems();
return specialtyList;
}
}
// data access
public IEnumerable<SelectListItem> GetPlannedSpecialtyDdlItems()
{
IEnumerable<Specialty> specialties = this._context.Specialties().GetAll();
var selList = new List<SelectListItem>();
foreach (var item in specialties)
{
var tempps = new SelectListItem()
{
Text = item.Description,
Value = item.Id.ToString()
};
selList.Add(tempps);
}
return selList;
}
I would recommend you to avoid using ViewBag/ViewData/ Weekly typed code. Use strongly typed code and it makes it more readable. Do not use the Magic strings/ Magic variables. I would add a collection property to your ViewModel to hold the SelectList items and another property to hold the selected item value.
public class PlannedSpecialty
{
public IEnumerable<SelectListItem> SpecialtyItems { set;get;}
public int SelectedSpeciality { set;get;}
//Other Properties
}
and in your Get action, If you want to set some Item as selected,
public PartialViewResult PlannedSpecialty()
{
var pgtServ = new PgtService();
var vm=new PlannedSpecialty();
vm.SpecialtyItems = pgtServ.GetPlannedSpecialtyDropDownItems();
//just hard coding for demo. you may get the value from some source.
vm.SelectedSpeciality=25;// here you are setting the selected value.
return View(vm);
}
Now in the View, use the Html.DropDownListFor helper method
#Html.DropDownListFor(x=>x.SelectedSpeciality,Model.SpecialtyItems,"select one ")
Use the selected property of the SelectListItem class:
selList.Selected = true;

Categories