A dropdown list is a commonly used control in ASP.NET Core MVC for allowing users to select an option from a list of things. Frequently, the dropdown list control’s list of items includes a list of months from which the user can choose. Manually populating a dropdown list control with month names, on the other hand, might be time-consuming and inconvenient. In this post, we’ll look at how to use ASP.NET Core MVC | Populate DropdownList with Month Names Using LINQ.
Table of Contents
Prerequisites
You will need the following to follow along with this tutorial:
Steps for ASP.NET Core MVC | Populate DropdownList with Month Names Using LINQ
Create a Dropdownlist control.
First, in our Razor view, we need to add a Dropdownlist control.
@*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
ViewData["Title"] = "Home Page";
}
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Select Month</label>
<select nme="getMonth" class="form-control" asp-items="@ViewBag.Month"></select>
</div>
</div>
</div>
Create a List of Month Names
The next step is to make a list of month names. We’ll use LINQ to generate a list of months, with the current month set as the default value.
public IActionResult Index()
{
var GetMonth = Enumerable.Range(1,12)
.Select(m => new SelectListItem
{
Text = new DateTimeFormatInfo().GetAbbreviatedMonthName(m),
Value = m.ToString()
}).ToList();
ViewBag.Month = GetMonth;
return View();
}
More Related Posts
How to Create CRUD API in Asp.net CoreWith Postgresql How to execute stored procedure in Asp.Net CoreConclusion
Using LINQ to populate a Dropdownlist control with month names in ASP.NET Core is a simple process. You can rapidly construct a Dropdownlist control with a list of months for your users to select by following the methods explained in this article.
FAQs
- What exactly is LINQ?
LINQ is an acronym that stands for Language Integrated Query. It is a.NET language feature that allows developers to query several data sources using a uniform syntax.
2. Is it possible to associate the Dropdownlist control with a list of objects?
Yes, you may associate the Dropdownlist control with a collection of objects. Simply build a list of SelectListItem objects, where the Value property is the object’s ID and the Text property is the object’s name.