using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
namespace Clients.model
{
public class Class1
{
string cn= ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
public List<client> DropClient()
{
SqlConnection db = new SqlConnection(cn);
string query = "SELECT * FROM mytable"";
SqlCommand cmd = new SqlCommand(query,db);
db.Open();
List<client> list = new List<client>();
using (IDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
Client obj = new Client();
if (dataReader["ClientID"] != DBNull.Value)
{
if (dataReader["ClientID "] != DBNull.Value) { obj.ClientID= (int)dataReader["ClientID"]; }
if (dataReader["Nom"] != DBNull.Value) { obj.Nom= (string)dataReader["Nom"]; }
list.Add(obj);
}
}
return list;
}
}
}
and write controller something like this,
public ActionResult Create()
{
Class1 dbconnection = new Class1();
List<Client> pcontent = new List<Client>();
{
pcontent = dbconnection.DropClient();
};
List<SelectListItem> clientList= new List<SelectListItem>();
//List<string> items = new List<string>();
foreach (var item in pcontent)
{
clientList.Add(new SelectListItem
{
Text = item.No,
Value = item.ClientID.ToString()
});
}
ViewBag.clientList= clientList;
return View();
}
and create a view
@Html.DropDownList("Clients", (IEnumerable<SelectListItem>)ViewBag.clientList,"-- Select --")
hope this will help you