In this article I will explain with an example, how to set ListBox selected value from
SQL Server database in ASP.Net Core 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.
Database Context
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using Microsoft.EntityFrameworkCore;
namespace ListBox_Selected_DB_Core
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<HobbyModel> Hobbies { get; set; }
}
}
Model
You will need to import the following namespaces.
public class HobbyModel
{
[Key]
public int HobbyId { get; set; }
public string Hobby { get; set; }
public bool IsSelected { get; set; }
}
Controller
The Controller consists of following Action method.
Action Method for handling GET operation
Inside this Action method, first the connection is read from the ConnectionStrings section of the AppSettings.json file.
Then, the records are fetched from the
Hobbies Table using
Entity Framework and set to the respective properties of
SelectListItem class object.
Finally, the Generic List collection of SelectListItem class object is returned to the View.
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
List<SelectListItem> hobbies = (from hobby in this.Context.Hobbies
select new SelectListItem
{
// Set the Text.
Text = hobby.Hobby,
// Set the Value.
Value = hobby.HobbyId.ToString(),
// Set the Selected value.
Selected = Convert.ToBoolean(hobby.IsSelected)
}).ToList();
return View(hobbies);
}
}
View
HTML Markup
Inside the View, first the Generic List collection of SelectListItem class is declared as Model and the ASP.Net TagHelpers is inherited.
The View consists of an HTML SELECT (ListBox) element to which the TagHelper attribute i.e. asp-items is set to Model and multiple property is set to multiple.
@model List<SelectListItem>
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
Hobbies:
<br />
<select id="lstHobbies" asp-items="Model" multiple="multiple"></select>
</body>
</html>
Screenshot
Demo
Downloads