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 |
- BindingFlags.Instance);
- List<string> tbllistname = new List<string>();
- foreach (var item in mytables)
- {
- tbllistname.Add(item.Name.Split('<', '>')[1]);
- }
- ViewBag.MyTables = tbllistname;
- }
- return View();
- }
- }
- }
- ViewBag.Title = "Index";
- }
- <h2 class="text-info">Welcome my dropdown list example</h2>
- <table>
- <tr>
- <td>
- @Html.DropDownList("tables", new SelectList(ViewBag.MyTables), new { id = "ddl1" })
- </td>
- </tr>
- </table>

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

Anees KhalidPosted Apr 17, 2019, 5:40 AM
Can Anyone Solve this Issue I need to show all the table names which are in my database into a dropdownlist. When table is selected then show Table columns in a GridView MVC Entity Framework
Anees KhalidPosted Apr 16, 2019, 7:53 AM
When You select particular table it does not show data
Vignesh ManiPosted Jul 4, 2016, 11:11 AM
Good one
RajaPosted Jul 4, 2016, 12:38 AM
Good One...
Prasanna MuraliPosted Jul 3, 2016, 11:12 AM
Nice one...
kalu singh raoPosted Jul 3, 2016, 4:25 AM
Nice...