Watch online:
1. Create new project (MVC 4)
2. Add entity connection
3. Add controller
4. Add
private CompanyTestDatabaseEntities db = new CompanyTestDatabaseEntities();
5. Add dispose method
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
6. Add Index Method - it will populate ViewBag with data from database
public ActionResult Index()
{
ViewBag.GroupId = new SelectList(db.GroupMasters, "GroupId", "GroupName");
return View();
}
7. Whole Controller code looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestPassingToDropDown.Models;
namespace TestPassingToDropDown.Controllers
{
public class FirstController : Controller
{
private CompanyTestDatabaseEntities db = new CompanyTestDatabaseEntities();
//
// GET: /First/
public ActionResult Index()
{
ViewBag.GroupId = new SelectList(db.GroupMasters, "GroupId", "GroupName");
return View();
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
8. Create view and add the following code to it
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>
@Html.DropDownList("GroupId", String.Empty)
</div>
9. That's it.