Dear AbushNasi,
Using the below article i have created the example.
Please refer below sample.
Model
public class FruitModel
{
public List<SelectListItem> Fruits { get; set; }
public int FruitId { get; set; }
}
Namespaces
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
FruitModel fruit = new FruitModel();
fruit.Fruits = PopulateFruits();
return View(fruit);
}
[HttpPost]
public ActionResult Index(FruitModel fruit)
{
fruit.Fruits = PopulateFruits();
foreach (SelectListItem item in fruit.Fruits)
{
if (item.Value == fruit.FruitId.ToString())
{
item.Selected = true;
break;
}
}
return View(fruit);
}
private List<SelectListItem> PopulateFruits()
{
List<SelectListItem> fruits = new List<SelectListItem>();
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT FruitId, FruitName FROM Fruits", con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
fruits.Add(new SelectListItem
{
Text = sdr["FruitName"].ToString(),
Value = sdr["FruitId"].ToString()
});
}
}
con.Close();
}
}
return fruits;
}
}
View
@model DropDown_selected_value.Models.FruitModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table>
<tr>
<td>
Fruit Name:
</td>
<td>
@Html.DropDownListFor(m => m.FruitId, new SelectList(Model.Fruits, "Value", "Text"), "Please select")
</td>
</tr>
</table>
<input type="submit" value="Submit" />
}
</body>
</html>
Screenshot