In this article, we discuss .Net Core: ADO.Net Tutorial with example. Also please go through our previous article Binding Dropdown List With Database in ASP.NET Core and Entity Framework.
➤ Bind Dropdownlist using ADO .NET in ASP .NET Core MVC
The records from the Database will be fetched from Database using ADO.Net into Model class object and then the Model is used to populate the DropDownList using the new ASP.Net Tag Helpers in ASP.Net Core MVC.
Fig-1 |
The sample SQL code are find below;
➥ Models : Create a model class of department inside Models folder as like below;
➥ Controllers : Navigate to HomeController.cs
Action method for handling GET operation
- Inside this Action method, the GetDepartmentDetails() method is called, the records from the Departments table are fetched from Database Table through a DataReader and generic list collection of DepartmentModel class is populated.
- Then generic list collection of DepartmentModel class objects is copied to ViewBag object which is used for populating DropDownList in .Net Core.
- This Action method handles the call made from the POST function from the View.
- When the Form is submitted, the Text and Value of the selected DropDownList Item are captured through the two parameters i.e. DeptId and DeptName.
- The values of DeptId and DeptName are fetched and are set into a ViewBag object which will be later displayed in View and append into a DIV.
➥ Views: Navigate to Index.cshtml
The View consists of an HTML Form with following ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
- The Form consists of a DropDownList, a Hidden Field and a Submit Button.
- The Model data has been assigned to the DropDownList using the asp-items Tag Helpers attribute;
- The DropDownList has been assigned a jQuery OnChange event handler, when an item is selected in the DropDownList, the Text of the selected item is copied in the Hidden Field.
- When the Submit Button is clicked, the Form gets submitted and the DeptId and DeptName values are sent to the Controller.
- Finally, the DeptId and DeptName values of the selected Fruit are displayed in a DIV html.
Now we are done with all changes, let's run our application and see output like below;
Fig-2 |
</> Find the Source Code in Github.com/CoreProgramm/
Summary
Post a Comment