Hi anjali600,
You need to make use of HiddenField to send the DropDownList Text to Controller.
Refer below example.
Database
This example makes use of a table named Fruits..
Download SQL File
Model
public class FruitModel
{
public int FruitId { get; set; }
public string FruitName { get; set; }
}
Namespaces
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
Controller
public class HomeController : Controller
{
public async Task<IActionResult> Index()
{
List<FruitModel> fruits = await Task.Run(() => PopulateFruits());
ViewBag.Fruits = new SelectList(fruits, "FruitId", "FruitName");
return View();
}
[HttpPost]
public async Task<IActionResult> Index(FruitModel model)
{
ViewBag.Message = "Fruit Name: " + model.FruitName;
ViewBag.Message += "\\nFruit Id: " + model.FruitId;
List<FruitModel> fruits = await Task.Run(() => PopulateFruits());
ViewBag.Fruits = new SelectList(fruits, "FruitId", "FruitName");
return View();
}
private static List<FruitModel> PopulateFruits()
{
string constr = @"Data Source=.\SQL2022;Initial Catalog=Test;uid=sa;pwd=pass@123;";
List<FruitModel> fruits = new List<FruitModel>();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT FruitName, FruitId FROM Fruits", 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
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model Bind_DropDownList_Core.Models.FruitModel
@{
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" asp-for="FruitId" asp-items="ViewBag.Fruits">
<option value="0">Please select</option>
</select>
<input type="hidden" asp-for="FruitName" />
<input type="submit" value="Submit" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/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