Hi sunkana,
Using the below article i have created the example.
You need to set the selected value after PostBack. Refer the below sample.
Model
public class FruitModel
{
[BindProperty]
public int FruitId { get; set; }
[BindProperty]
public string FruitName { get; set; }
}
Namespaces
using System.Data.SqlClient;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
IndexModel
public class IndexModel : PageModel
{
public SelectList Fruits { get; set; }
public void OnGet()
{
this.Fruits = new SelectList(PopulateFruits(), "FruitId", "FruitName");
}
public void OnPostSubmit(FruitModel fruit)
{
this.Fruits = new SelectList(PopulateFruits(), "FruitId", "FruitName");
string message = "Fruit Name: " + fruit.FruitName;
message += "\\nFruit Id: " + fruit.FruitId;
ViewData["Message"] = message;
ViewData["Selected"] = fruit.FruitId;
}
private static List<FruitModel> PopulateFruits()
{
string constr = @"Data Source=.;Initial Catalog=Sample;uid=sa;pwd=pass@123;";
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
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Razor_DropDownList_ADO.Net.Pages.IndexModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post">
<select id="ddlFruits" name="FruitId" asp-items="@Model.Fruits">
<option value="0">Please select</option>
</select>
<input type="hidden" name="FruitName" />
<input type="submit" value="Submit" asp-page-handler="Submit" />
</form>
<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 (ViewData["Message"] != null)
{
<script type="text/javascript">
$(function () {
alert("@ViewData["Message"]");
});
</script>
}
@if (ViewData["Selected"] != null)
{
<script type="text/javascript">
$(function () {
$("#ddlFruits").val("@ViewData["Selected"]");
});
</script>
}
</body>
</html>
Screenshot