To Populate a Dropdownlist with Selected Values from a Database in MVC, you should follow the below steps in details:
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);
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.
1.1k questions
673 answers
454 comments
193k users
Related Activities
Categories
Most popular tags