Add Table Names In Dropdown List With Entity Framework In ASP.NET MVC

Datetime:2016-08-23 04:40:15         Topic: ASP.NET MVC          Share        Original >>
Here to See The Original Article!!!

I am explaining in this article how to add the table name in the dropdown list from the database in MVC. Sometimes, we see the example in real time when we select the table name and display the respective results in the Gridview or the table etc. We will see step by step.

Step 1:We can see the number of tables in my database. My database name is System test.

Step 2:Now, we have to create an MVC Application to perform the task.

Open Visual Studio and take a new project.

Choose ASP.NET Web Application, give the name and click OK.

Now, we choose MVC option and click OK.

Step 3: Now, we have to add the model class. For this, we right click on MVC project and add ADO .NET Entity Data Model. Right click MVC project on Solution Explorer, select add option and proceed, as shown below:

Add EF Designer from the database and click Next button.

Add clicking new connection option, give the Server name, select the database, click Test Connection and click OK.

Click next and select the tables which you want. Here, I selected all the tables and clicked OK.

Click Finish.

Step 4: Now, we have to add the controller. Right click on the controller folder, as shown below:

Select 'Controller Empty' option and Click Add button.

Now we have to write the codes in the controller class.

First, we have to add a namespace, shown below:

Using System.Reflection;

Now, write the full codes, given below:

using System.Collections.Generic;  
using System.Reflection;  
using System.Web.Mvc;  
namespace TablesWithDropdownExa.Controllers  
    public class MyControllerController : Controller  
        // GET: MyController  
        public ActionResult Index()  
            using (var Mydb = new SystemTestEntities())  
                FieldInfo[] mytables = Mydb.GetType().GetFields(BindingFlags.Public |  
                                       BindingFlags.NonPublic |  
                List<string> tbllistname = new List<string>();  
                foreach (var item in mytables)  
                    tbllistname.Add(item.Name.Split('<', '>')[1]);  
                ViewBag.MyTables = tbllistname;  
                return View();  

Now, we have to add the view. For this, right click the index method, add the view and write the codes in Index.chtml page.

    ViewBag.Title = "Index";  
<h2 class="text-info">Welcome my dropdown list example</h2>  
            @Html.DropDownList("tables", new SelectList(ViewBag.MyTables), new { id = "ddl1" })  

And finally see the result,

I hope you enjoyed this. Thank you for looking at the example.

About List