Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dropdown list from dictionary mvc

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

like image 717
Abdalla Ismail Avatar asked Apr 26 '26 07:04

Abdalla Ismail


1 Answers

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")
    )
like image 57
Daniel Hoffmann-Mitscherling Avatar answered Apr 29 '26 04:04

Daniel Hoffmann-Mitscherling