how to bind dropdownlist from two table in mvc using entity framework

Posted by Shail under ASP.NET MVC on 7/5/2014 | Points: 10 | Views : 12126 | Status : [Member] | Replies : 2
how to bind data in dropdownlist from two table in mvc4.0 Razor using entity framework

plz help me


Posted by: Sheonarayan on: 7/5/2014 [Administrator] HonoraryPlatinum | Points: 25

Hi Shail,

Below is the exact code snippet of how you would bind data in DropDownList from two tables in mvc using Entity Framework.

DropDownList Code
@Html.DropDownList("MultipleTables", ViewBag.Roles as SelectList)

Action Method code of the controller
public ActionResult Create()
var data = from p in db.PersonalDetails
join f in db.Files
on p.AutoId equals f.PersonalDetailsId
select new
PersonName = p.FirstName,
MyFileName = f.FileName

SelectList list = new SelectList(data, "MyFileName", "PersonName");
ViewBag.Roles = list;

return View();

In the above code snippet, we are joining PersonalDetails and Files tables using LINQ (Know more about join in LINQ and getting FirstName as PersonName and FileName as MyFileName property of the object.

The same is being converted into SelectList by specifying the dataTextField and dataValueField and then set as ViewBag.Roles

This ViewBag.Roles is being given as data source of the Html.DropDownList in the View (first code snippet).

Hope this helps.


Sheo Narayan

Shail, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Goud.Kv on: 7/5/2014 [Member] [MVP] Gold | Points: 25

Hello Shail.,

Please read the below article regarding Dropdowns in MVC,

Hope this helps you,

Thanks & Regards,

Shail, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response