I am explaining how to add the table name in the dropdown list from the database in mvc. Sometimes we see the example in real-time that we select table name and display the respective result in grid view or table or any else like that. We see step by step.
Step 3:
Now we have to write codes in a controller class.
I hope you enjoyed. Thank you see the example.
Step 1:
We can see the numbers of tables in my database. And here my database name
is System test.
Step 2:
Now we have to
create an mvc application for performing the task.
- Open Visual studio and take a new project.
- Choose ASP.NET Web Application and give name click ok.
- Now we choose the MVC option and click ok.
- Now we have to add a model class so for this, we right-click of MVC project and add the ADO .Net Entity Data Model. So right click mvc project on solution explore and select add option and select.
- Add EF Designer from database and click the Next button.
- Add click new connection option and give the server name and select the database and click Test Connection and click OK.
- Click Next and select the tables which are you want here I selected all tables and click OK.
- Click Finish
- Now we have to add a controller, so right click of controller’s folder
- Select 'Controller Empty' option and Click Add button.
Now we have to write codes in a controller class.
First, we have to add a namespace
using System.Reflection;
Now write full codes
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();
}
}
}
Now we have to add view so for this right click index method and add
view and write codes in Index.chtml page.
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>
And finally, see the result
I hope you enjoyed. Thank you see the example.
No comments:
Post a Comment