Hi akhter,
Use DropDownListFor.
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Model
public class tbl_Student
{
public string std_id { get; set; }
public string std_Name { get; set; }
public List<SelectListItem> ClassList { get; set; }
public string ClassId { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
tbl_Student student = new tbl_Student();
student.ClassList = GetClasss();
ViewBag.saveresult = "";
return View(student);
}
[HttpPost]
public ActionResult Index(tbl_Student student)
{
using (NorthwindEntities entities = new NorthwindEntities())
{
Customer s = new Customer();
s.CustomerID = student.std_id;
s.ContactName = student.std_Name;
entities.Customers.Add(s);
entities.SaveChanges();
ViewBag.saveresult = "Data Save";
ModelState.Clear();
}
return View(new tbl_Student() { ClassList = GetClasss() });
}
private static List<SelectListItem> GetClasss()
{
NorthwindEntities entities = new NorthwindEntities();
List<SelectListItem> classList = (from p in entities.Customers
select new SelectListItem
{
Text = p.ContactName,
Value = p.CustomerID.ToString()
}).ToList();
//Add Default Item at First Position.
classList.Insert(0, new SelectListItem { Text = "--Select Class--", Value = "" });
return classList;
}
}
View
@model DropDownList_MVC.Models.tbl_Student
@{
Layout = null;
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<script>
</script>
</head>
<body>
<h1>
Study
</h1>
<h4>
Insert Data into Database AKhter
</h4>
<div>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table border="1" bgcolor="yellow" width="400px" height="250px">
<tr>
<td>Roll Number</td>
<td> @Html.TextBoxFor(m => m.std_id, "{0:#.#}")</td>
</tr>
<tr>
<td>
Student Name
</td>
<td> @Html.TextBoxFor(m => m.std_Name)</td>
</tr>
<tr>
<td>
Class
</td>
<td>
@Html.DropDownListFor(m => m.ClassId, Model.ClassList)
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
<tr></tr>
</table>
}
</div>
<b>@ViewBag.saveresult</b>
</body>
</html>
Screenshot
You will get the dropdownlist selected value inside the model class property.