In this article I will explain with an example, how to use
SelectList class in
ASP.Net Core (.Net Core 8)
MVC.
Database
I have made use of the following table Fruits with the schema as follow.
The Fruits table has the following records.
Note: You can download the database table SQL by clicking the download link below.
Model
The Model class consists of following properties FruitId and FruitName.
public class FruitModel
{
public int FruitId { get; set; }
public string FruitName { get; set; }
}
Namespaces
You will need to import the following namespace.
using Microsoft.Data.SqlClient;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, the PopulateFruits method is called.
Inside the PopulateFruits method, the records from the Fruits table are fetched from Database Table through a DataReader and generic list collection of FruitModel class is populated.
Then generic list collection of
FruitModel class objects is copied to
SelectList class object which is used for populating
DropDownList in .Net Core.
Finally, the SelectList class object is sent to the View.
Action method for handling POST operation
This Action method handles the call made from the POST function from the View.
When the Form is submitted, the
Text and
Value of the selected
DropDownList Item are captured through the two parameters i.e.
fruitId and
fruitName.
The values of
FruitId and
FruitName are fetched and are set into a
ViewBag object which will be later displayed in View using
JavaScript Alert Message Box.
public class HomeController : Controller
{
public IActionResult Index()
{
List<FruitModel> fruits = PopulateFruits();
return View(new SelectList(fruits, "FruitId", "FruitName"));
}
[HttpPost]
public IActionResult Index(string fruitId, string fruitName)
{
ViewBag.Message = "Fruit Name: " + fruitName;
ViewBag.Message += "\\nFruit Id: " + fruitId;
return View();
}
private static List<FruitModel>PopulateFruits()
{
string constr = @"Data Source=.\SQL2019;Initial Catalog= AjaxSamples;uid=sa;pwd=pass@123;TrustServerCertificate=True";
List<FruitModel> fruits = new List<FruitModel>();
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT FruitName, FruitId FROM Fruits";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
fruits.Add(new FruitModel
{
FruitName = sdr["FruitName"].ToString(),
FruitId = Convert.ToInt32(sdr["FruitId"])
});
}
}
con.Close();
}
}
return fruits;
}
}
View
HTML Markup
Inside the View, in the very first line
ASP.Net TagHelpers is inherited.
The View consists of an
HTML Form with following
ASP.Net TagHelpers 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 Form consists of a
DropDownList, a
Hidden Field and a
Submit Button.
The Model data has been assigned to the
DropDownList using the asp-items
Tag Helpers attribute;
The
DropDownList has been assigned a
jQuery OnChange event handler, when an item is selected in the
DropDownList, the Text of the selected item is copied in the Hidden Field.
When the Submit Button is clicked, the Form gets submitted and the FruitId and FruitName values are sent to the Controller.
Finally, the
FruitId and
FruitName values of the selected Fruit are displayed using
JavaScript Alert Message Box.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model SelectList
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index">
<select id="ddlFruits" name="FruitId" asp-items="Model">
<option value="0">Please select</option>
</select>
<input type="hidden" name="FruitName" />
<input type="submit" value="Submit" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$("body").on("change", "#ddlFruits", function () {
$("input[name=FruitName]").val($(this).find("option:selected").text());
});
</script>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
$(function () {
alert("@ViewBag.Message");
});
</script>
}
</form>
</body>
</html>
Screenshot
Downloads