I want to load data from database table's Column (1 Column only) in a dropdown using MVC.
Asked
Active
Viewed 735 times
2 Answers
2
Add the List to your model:
public List<string> DropDownList= new List<string>();
and then in your model create a function to load the data for the DropDownList from the database:
public void GetDropDownList()
{
//Pass your data base connection string here
using (SqlConnection c = new SqlConnection(cString))
//Pass your SQL Query and above created SqlConnection object "c"
using (SqlCommand cmd = new SqlCommand("SELECT Column1 FROM Table", c))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
DropDownList.Add(rdr["Column1"].ToString())
}
}
}
}
and then in Controller finally, you need to send your model to the view:
//Create object of your Model of controller
Model objModel = new Model();
//Call function to load the data for the DropDownList
objModel.GetDropDownList();
//return view with your object of model
return View(objModel);
Now in the Razor you can display this:
@Html.DropDownListFor(m => Model.DropDownList);

Pranav_Systematix
- 355
- 2
- 8
-1
Please post your code to have a better solution.Otherwise you could use the foreach loop of the data about the li(html) elements.

Shubham Bansal
- 586
- 6
- 7