Hi leila398,
Check this example.
Using this article i have created the example.
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();
var selectedItem = fruit.Fruits.Find(p => p.Value == fruit.FruitId.ToString());
if (selectedItem != null)
{
selectedItem.Selected = true;
ViewBag.Message = "Fruit: " + selectedItem.Text;
}
return View(fruit);
}
private static List<SelectListItem> PopulateFruits()
{
List<SelectListItem> items = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
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())
{
items.Add(new SelectListItem
{
Text = sdr["FruitName"].ToString(),
Value = sdr["FruitId"].ToString()
});
}
}
con.Close();
}
}
return items;
}
}
View
@model DropDownListFor_MVC.Models.FruitModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
</head>
<body class="container">
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table>
<tr>
<td>
Fruit:
</td>
<td>
@Html.DropDownListFor(m => m.FruitId, Model.Fruits, "Please select", new { @class = "form-control" })
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshot