In this article I will explain with an example, how to update Database Table using ListBox in ASP.Net Core (.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.
Model
The following two Models are created.
HobbyModel
public class HobbyModel
{
[Key]
public int HobbyId { get; set; }
public string Hobby { get; set; }
public bool IsSelected { get; set; }
}
Hobby
public class Hobby
{
public List<SelectListItem> Hobbies { get; set; }
public List<string> HobbyIds { get; set; }
}
Database Context
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using ListBox_Update_DB_Core.Models;
using Microsoft.EntityFrameworkCore;
namespace ListBox_Update_DB_Core
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<HobbyModel> Hobbies { get; set; }
}
}
Controller
The Controller consist of following Action methods.
Action method for handling GET operation
Inside this Action method, an object of HobbyModel class is created and its Hobbies property is set with the Generic List collection i.e. records of the Hobbies Table which is returned from the PopulateHobbies method (explained later).
PopulateHobbies
Inside this method, the records are fetched from the
Hobbies Table using
Entity Framework and added to the Generic List collection of
SelectListItem class which is finally returned.
Action method for handling POST operation
This Action method gets called when Submit Button is clicked which accepts HobbyModel class object as a parameter.
Inside this Action method, first the Hobbies property of HobbyModel class is set with the records returned from the PopulateHobbies method (explained earlier).
Then, a check is performed if the HobbyIds property is NULL or not, if not NULL then a FOR EACH loop is executed over the Generic List collection of Hobbies.
Inside the loop, the UpdateHobby method (explained later) is called which accepts the value i.e. HobbyId and the status of that Hobby whether it is selected or not.
Note: The status is determined based on the presence of that HobbyId in the Generic List collection of string created earlier in the HobbyModel class.
Finally, the success message is set into a
ViewBag object and the object of
HobbyModel class is returned to the View.
UpdateHobby
Inside this method, a check is performed whether the HobbyId of the current item of the ListBox is present in the HobbyId i.e. Model property and if found then IsSelected property is set based on the value accepted as parameter.
Finally, the SaveChanges method of DbContext is called which updates the records in the Database Table.
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
Hobby hobbyModel = new Hobby();
hobbyModel.Hobbies = this.PopulateHobbies();
return View(hobbyModel);
}
[HttpPost]
public ActionResult Index(Hobby hobby)
{
hobby.Hobbies = this.PopulateHobbies();
if (hobby.HobbyIds != null)
{
foreach (SelectListItem item in hobby.Hobbies)
{
this.UpdateHobby(int.Parse(item.Value), hobby.HobbyIds.Contains(item.Value));
}
ViewBag.Message = "Records successfully updated!";
}
return View(hobby);
}
private void UpdateHobby(int hobbyId, bool isSelected)
{
HobbyModel hobby = (from h in this.Context.Hobbies
where h.HobbyId == hobbyId
select h).FirstOrDefault();
hobby.IsSelected = isSelected;
this.Context.SaveChanges();
}
private List<SelectListItem>PopulateHobbies()
{
List<SelectListItem> hobbies = (from hobby in this.Context.Hobbies
select new SelectListItem
{
Text = hobby.Hobby,
Value = hobby.HobbyId.ToString()
}).ToList();
return hobbies;
}
}
View
HTML Markup
Inside the View, in the very first line the HobbyModel class is declared as Model for the View and the ASP.Net TagHelpers is also inherited.
The View consists of an HTML Form with following ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The View consists of an HTML INPUT SELECT element which has been assigned with the multiple property set to multiple that makes it a ListBox element.
The ListBox has been also assigned with the model property.
The View also consists of a Submit Button.
Submitting the Form
When the
Submit Button is clicked then, the
ViewBag object is checked for NULL and if it is not NULL then, the value of the
ViewBag object is displayed using
JavaScript Alert Message Box.
@model ListBox_Update_DB_Core.Models.Hobby
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
#lstHobbies { width: 150px; height: 150px }
</style>
</head>
<body>
<form asp-action="Index" asp-controller="Home" method="post">
Hobbies:
<br /><br />
<select id="lstHobbies" asp-items="Model.Hobbies" multiple="multiple" name="HobbyIds">
</select>
<br /><br />
<input type="submit" value="Save" />
</form>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshots
Form
Record before Updating
Records after Updating
Downloads