How to fetch data from database to dropdown in ASP.Net MVC using separ
The text of this thread is not in this database — only its details are. Read it on the old site: How to fetch data from database to dropdown in ASP.Net MVC using separ
The text of this thread is not in this database — only its details are. Read it on the old site: How to fetch data from database to dropdown in ASP.Net MVC using separ
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jayraj ChhayaRank #304 · 8.2K reputationPosted Jan 29, 2024, 2:33 AM EST
To fetch data from a database and populate a dropdown list in an ASP.Net MVC application using Entity Framework, you can follow these steps:
Create a model class for the data you want to fetch from the database. For example, if you want to fetch a list of categories, create a
Categorymodel class with properties likeIdandName.Create a DbContext class that inherits from
DbContextand represents your database context. This class will have aDbSetproperty for the model class you created in the previous step. For example, if you created aCategorymodel class, your DbContext class will have aDbSetproperty.Use Entity Framework to query the database and retrieve the data you need. In your controller action method, create an instance of your DbContext class and use LINQ queries to fetch the data. For example, to fetch a list of categories, you can use
dbContext.Categories.ToList().Pass the fetched data to the view. Create a view model class that represents the data you want to display in the dropdown list. For example, if you want to display the category names in the dropdown list, create a view model class with a property like
List CategoryNames .In your controller action method, populate the view model with the fetched data and pass it to the view. For example, if you have a view model class named
CategoryViewModel, you can populate itsCategoryNamesproperty with the category names fetched from the database.In your view, use the
Html.DropDownListForhelper method to render the dropdown list. Pass the view model property that contains the data as the data source for the dropdown list. For example, if your view model has a property namedCategoryNames, you can useHtml.DropDownListFor(m => m.SelectedCategory, new SelectList(Model.CategoryNames)).Vishal YelveRank #178 · 13.6K reputationPosted Jan 29, 2024, 2:46 AM EST
Hi Rutwik,
Do refer below article
https://www.aspsnippets.com/Articles/2484/Populate-Bind-DropDownList-from-ViewModel-in-ASPNet-MVC/