I am trying to bind departments in dropdownlist in mvc from sql server database. I have created model, controller and view for that. The project is running file without any error but still it is not filling the departments from the database in my dropdownlist.
Below are the database script and the code
I have a database named “Dbemp” and in that I have a table Department as shown below srcipt
USE [Dbemp]
GO
CREATE TABLE [dbo].[Department](
[DeptId] [int] IDENTITY(1,1) NOT NULL,
[DeptName] [varchar](50) NOT NULL,
PRIMARY KEY CLUSTERED
(
[DeptId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
My Department Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace DynamicDropDownListMVC.Models
{
public class Department
{
[Key]
public int DeptId { get; set; }
public string DeptName { get; set; }
}
}
My connectionstring in web.config file
<connectionstrings>
<add name="MyDBContext" connectionstring="Data Source=My-PC;Initial Catalog=Dbemp;Integrated Security=True" providername="System.Data.SqlClient" />
</connectionstrings>
My Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DynamicDropDownListMVC.Models;
namespace DynamicDropDownListMVC.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
MyDBContext db = new MyDBContext();
var data = db.Departments.ToList();
ViewBag.Departments = new SelectList(db.Departments, "DeptId", "DeptName");
return View();
}
}
}
My View:
@{
ViewBag.Title = "Home Page";
}
@Html.DropDownList("Departments", "Select Department")