Hi moepyag,
Refer below example.
Controller
public class HomeController : Controller
{
public IActionResult Index()
{
return View(this.PopulateYears());
}
[HttpPost]
public IActionResult Index(string yearValue, string year)
{
ViewBag.Message = "Selected Text: " + year;
ViewBag.Message += "\\nSelected Value: " + yearValue;
return View(this.PopulateYears());
}
private SelectList PopulateYears()
{
List<SelectListItem> years = new List<SelectListItem>();
for (var i = 2000; i <= DateTime.Now.Year; i++)
{
years.Add(new SelectListItem
{
Text = i.ToString(),
Value = (i - 2000).ToString()
});
}
return new SelectList(years, "Value", "Text");
}
}
View
@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="ddlYears" name="YearValue" asp-items="Model">
<option value="0">Please select</option>
</select>
<input type="hidden" name="Year" />
<input type="submit" value="Submit" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$("body").on("change", "#ddlYears", function () {
$("input[name=Year]").val($(this).find("option:selected").text());
});
</script>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
$(function () {
alert("@ViewBag.Message");
});
</script>
}
</form>
</body>
</html>
Screenshot