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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Vishal YelvePosted Jan 29, 2024, 7:46 AM
Hi Rutwik,
Do refer below article
https://www.aspsnippets.com/Articles/2484/Populate-Bind-DropDownList-from-ViewModel-in-ASPNet-MVC/
Jayraj ChhayaPosted Jan 29, 2024, 7:33 AM
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)).