Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
1.2k views
in .Net Framework by 39 42 54
I am working on an MVC solutions and I want to Populate a Dropdownlist with Selected Values from a Database in MVC , How can I do that in MVC?

1 Answer

0 like 0 dislike
by 39 42 54
selected by
 
Best answer

How to retrieve a Selected Values from a Database in MVC?

To Populate a Dropdownlist with Selected Values from a Database in MVC, you should follow the below steps in details:

  1. In the Controller, You can retrieve all lookup data related to the dropdownlist, as demonstrated in the example below with 'departments'.

        ViewBag.DepartmentId = new SelectList(lookupService.GetAllDepartment(), "Id", "NameAr", 5);
    
  2. In the View, you can showcase data from ViewBag.DepartmentId by utilizing the following code:

      <div class="col-md-12 mb-3">
         @Html.Label(Resources.Labels.LblDepartmentId, new { @class = " form-label", @for = "DepartmentId" })
         @Html.DropDownList("DepartmentId", null, Resources.Labels.SelectFromMenu, new { @id = "DepartmentId", @class = "form-control form-select" })
     </div> 
    
  • lookupService.GetAllDepartment() : To obtain all departments from the database, you can use the code snippet provided below to retrieve the data, using Clean Code .
  • Number 5 : This is specifically intended for numeric values that correspond to database IDs.
If you don’t ask, the answer is always NO!
...