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




Responses

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

Up
0
Down
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 http://www.dotnetfunda.com/codes/show/1849/how-to-use-left-right-outer-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.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

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

Up
0
Down
Hello Shail.,

Please read the below article regarding Dropdowns in MVC,
http://www.dotnetfunda.com/articles/show/2918/working-with-dropdownlist-in-aspnet-mvc

Hope this helps you,

Thanks & Regards,
Krishna

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

Login to post response