Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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


SQL
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
C#
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
HTML
<connectionstrings>
    <add name="MyDBContext" connectionstring="Data Source=My-PC;Initial Catalog=Dbemp;Integrated Security=True" providername="System.Data.SqlClient" />  
  </connectionstrings>


My Controller
C#
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:
Razor
@{
    ViewBag.Title = "Home Page";
}

@Html.DropDownList("Departments", "Select Department")
Posted
Updated 14-Jan-15 18:58pm
v3

I think the way you have coded the
HTML
@Html.DropDownList("Departments", "Select Department")

Is wrong
Try using like below,
HTML
@Html.DropDownListFor(m=>m.name, (SelectList)ViewBag.DropdownListOptions)


This is because you need to specify the model property, here i have mentioned m=>m.name for showing an example. You need to write m=>m.departments.
I see here you have not used any viewmodel. It is better you use viewmodel here.

Check here for better understanding[^]

I hope my words help you.
Thanks
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900