I have this model
public class ExistingPlant
{
public Dictionary<Guid,string> plantList { get; set; }
}
and this is my code in the controller:
public ActionResult CreateFrom()
{
ExistingPlant existing = new ExistingPlant();
Dictionary<Guid, string> plants = new Dictionary<Guid, string>();
foreach(var item in context.Plants){
plants.Add(item.PlantId , item.ScientificName);
}
existing.plantList = plants;
return View();
}
I need help to create the dropdown list for the dictionary in my view.Any help please
This will bind to the form in mvc and pass the model back to the controller on submit with a selectedPlant.
Warning: Some efficiency and best practices [Mostly naming conventions] were ignored in the following code, it's simply based off what you posted.
Model:
public class ExistingPlant
{
public string selectedPlant { get; set; }
public Dictionary<Guid,string> plantList { get; set; }
}
Controller:
public ActionResult CreateFrom()
{
ExistingPlant existing = new ExistingPlant();
Dictionary<Guid, string> plants = new Dictionary<Guid, string>();
foreach(var item in context.Plants){
plants.Add(item.PlantId , item.ScientificName);
}
existing.plantList = plants;
existing.selectedPlant = "Value"; //Setting preselected value.
return View(existing); //Pass the model to the view
}
View:
@model ExistingPlant
@Html.DropDownListFor(
m => m.selectedPlant,
new SelectList(Model.plantList, "Value", "Key")
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With