In this article I will explain with an example, how to set ListBox selected value from
SQL Server database in ASP.Net MVC.
Database
I have made use of the following table Hobbies with the schema as follow.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Namespaces
You will need to import the following namespaces.
using System.Data.SqlClient;
using System.Configuration;
Controller
The Controller consists of following Action method.
Action Method for handling GET operation
Inside this Action method, first the generic List collection of SelectListItem class object is created and connection is read from the Web.Config file.
A connection to the database is established using the SqlConnection class.
Then, using ExecuteReader method, the records are fetched from the Hobbies Table and set to the respective properties of SelectListItem class object.
Finally, the SelectListItem class object is added to the Generic List collection of SelectListItem class object which finally returned to the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<SelectListItem> hobbies = new List<SelectListItem>();
string sql = "SELECT HobbyId, Hobby, IsSelected FROM Hobbies";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
SelectListItem item = new SelectListItem();
// Set the Text.
item.Text = sdr["Hobby"].ToString();
// Set the Value.
item.Value = sdr["HobbyId"].ToString();
// Set the Selected value.
item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
hobbies.Add(item);
}
}
con.Close();
}
}
return View(hobbies);
}
}
View
HTML Markup
Inside the View, first the Generic List collection of SelectListItem class is declared Model.
The View consists of a ListBox element created using Html.ListBox Helper method.
@model List<SelectListItem>
@{
Layout = null;
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
Hobbies:
<br />
@Html.ListBox("Hobbies", Model)
</body>
</html>
Screenshot
Demo
Downloads