Friday, 28 January 2022

Asp.Net Core 6: Bind DropdownList And Display In Table & Access Selected Value (Webgrid) Using C#.Net

1/28/2022 - By Pranav Singh 2

In this article i will show you how you can bind the dropdown list and show in each row  of table in asp.net core or mvc application using c#.net. 


Other Articles: Asp.Net Core 6: How To Bind DropDownList From DataBase Using C#.NetAsp.Net Core 6: Add(Create) Dynamic Row With TextBox/TextBoxFor To Table and Get Control Value at Controller End, jQuery, C#.NetAsp.Net Core 6: How to Search/Find Data Between Two Dates In MS Sql , Linq, C#.netSearch And Display Data In Table/Tabular Format in Asp.net Core 6/MVC using C# (Ms Sql Server).


For this article fist we will create two tables in our sql server database. First for department and second one is for employee detail.




Now for this article we will create a asp.net core 6 application and install below two mention packages for performing EntityFramework operations. 


Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools


Now we will run scamfld command to import all sql table objects as entityframework. 


Scaffold-DbContext "Server=..\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir data

 

Now here is the table objects. In this we are having department and employee table. In this we saving department id as a reference. 


Entity Table objects

Now we will create a model class to bind the view.

using Microsoft.AspNetCore.Mvc.Rendering;

using System.Collections.Generic;

 

namespace Project.Models

{

    public class EmployeeModel

    {

        public int[] DepartmentId { get; set; }

        public List<EmployeeDetail> EmployeeList { get; set; }

    }

    public class EmployeeDetail

    {

        public int Id { get; set; }

        public string EmployeeName { get; set; }

        public string Location { get; set; }

        public List<SelectListItem> DepartmentList { get; set; }

    }

}


Now we will make code to get the data from database and bind it to the model class to display it to the view. 


using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.Rendering;

using Project.data;

using Project.Models;

using System;

using System.Collections.Generic;

namespace Project.Controllers

{

    public class HomeController : Controller

    {

        [HttpGet]

        public IActionResult Index()

        {

            EmployeeModel employeeModel = new EmployeeModel();

            employeeModel.EmployeeList = new List<EmployeeDetail>();

            //Department list

            List<SelectListItem> department = new List<SelectListItem>(); 

            TestDBContext testDBContext = new TestDBContext();

            //Get department list

            var depdata = testDBContext.Departments;

            department.Add(new SelectListItem

            {

                Text = "Select Department",

                Value = ""

            });

            foreach (var ditem in depdata)

            {

                department.Add(new SelectListItem

                {

                    Text = ditem.DepartmentName,

                    Value = Convert.ToString(ditem.Id)

                });

            }

            //bind employee data

            var empdata = testDBContext.Employees;

            foreach (var item in empdata)

            {

                employeeModel.EmployeeList.Add(new EmployeeDetail

                {

                    EmployeeName = item.EmployeeName,

                    Id = item.Id,

                    Location = item.Location,

                    DepartmentList = department

                });

            }

            return View(employeeModel);

        }

        [HttpPost]

        public IActionResult Index(EmployeeModel employeeModel)

        {

            //Now save the department id in the database as required

            //Rebind the employee table data again 

            return View();

        }

    }

}


In above first we will discuss about HttpGet method. In this i have created the object of the mode class. After creating object i have prepared the list of department, and after getting the data of department i have passed it to the lit of the to the employee list. 


Now in HttpPost method i have passed the model class as a parameter. In this we will get the dropdown selected value which is present in table. 


Now i have passed the model object to the view. Now we will create the view.


@model Project.Models.EmployeeModel

@{

    ViewData["Title"] = "Upload  Page";

}

 

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))

{

    <div class="text-center">

        <table class="table table-bordered">

            <thead>

                <tr>

                    <th>Id</th>

                    <th>Employee Name</th>

                    <th>Location</th>

                    <th>Department</th>

                </tr>

            </thead>

            <tbody>

                @{int count = 0;

                    foreach (var item in Model.EmployeeList)

                    {

                        <tr>

                            <td>@item.Id</td>

                            <td>@item.EmployeeName</td>

                            <td>@item.Location</td>

                            <td>@Html.DropDownList("DepartmentId[" + count + "]", new SelectList(item.DepartmentList, "Value", "Text"))</td>

                        </tr>

                        count = count + 1;

                    }

                }

            </tbody>

        </table>

        <input type="submit" value="Submit" /><br />

    </div>

}


In above code i have i have prepared the model collection data to display the data. For department list i have taken dropdownlist. In this i have prepared the name of dropdonlist as an array. So that when postback take place we should be able to get the selected value. Now we have done run the code to check the output.


employee table in asp.net core

Now select the dropdown value an click on submit.

department selected data

Ones you click on submit button you will get the selected department list at controller end.


controller data

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

2 comments:

  1. Hi, great article, thank you. Am new to all of this. I get errors CS0029 and CS0246 when replicating this, as doesn't recognise EmployeeDetail ??

    ReplyDelete
    Replies
    1. Hi thanks for the comment. There was an mistake in the model class name. I have corrected it. Please check the :
      public class EmployeeModel

      {

      public int[] DepartmentId { get; set; }

      public List EmployeeList { get; set; }

      }

      public class Employee

      {

      public int Id { get; set; }

      public string EmployeeName { get; set; }

      public string Location { get; set; }

      public List DepartmentList { get; set; }

      }

      Delete

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top