Hi samirwarsi,
Using the article i have created an example using Data Access Object.
Refer below code.
Namespaces
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
DAL
public static class DAL
{
public static DataTable GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query, con);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
DAO
public static class DAO
{
public static List<SelectListItem> PopulateFruits()
{
List<SelectListItem> items = new List<SelectListItem>();
DataTable dt = DAL.GetData("SELECT FruitId, FruitName FROM Fruits");
foreach (DataRow row in dt.Rows)
{
items.Add(new SelectListItem
{
Text = row["FruitName"].ToString(),
Value = row["FruitId"].ToString()
});
}
return items;
}
}
Model
public class FruitModel
{
public List<SelectListItem> Fruits { get; set; }
public int? FruitId { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
FruitModel fruit = new FruitModel();
fruit.Fruits = DAO.PopulateFruits();
return View(fruit);
}
}
View
@model DropDownListFor_MVC.Models.FruitModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
body { font-family: Arial; font-size: 10pt; }
</style>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table>
<tr>
<td>Fruit:</td>
<td>@Html.DropDownListFor(m => m.FruitId, Model.Fruits, "Please select")</td>
</tr>
</table>
}
</body>
</html>
Screenshot