Tuesday, 25 January 2022

Asp.Net Core 6: Bind DropDownList and Access Selected Value In Controller Using C#.Net

1/25/2022 - By Pranav Singh 9

In this article i will show you how you can bind DropDownList control and access selected value at controller end in your asp.net core 6/mvc application from database data using c#.net. 


Other Articles: Asp.Net Core 6: Connect To Sql Server Database With Entity Framework Using C#Registration and Login Form Creation In Asp.net Core 6 Using C#.Net  From DatabaseAccess Connection String In Asp.Net Core 6 ClassLibrary From appsettings.json C#Asp.net Core 6: Ajax Login Form Using jQuery, C# Validate From Ms Sql Server Database


Now we will create a table named as employee and add the data in it.


Employee Table SQL

Now for this article fist we will create a new asp.net core 6 application. After creating asp.net core 6 web application we need to install below mention two packages from nuget package  manager. 

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

Now we need to run the below mention command to create the DB context. 

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

After this we will get all the entity table as a class file in mention data folder. 


entity table

Now we will create controller class file and add the below mention HTTPGET method. 


[HttpGet]

        public IActionResult Index()

        {

            return View();

        }


Now we will create the model class file and add the below mention code.


using Microsoft.AspNetCore.Mvc.Rendering;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks; 

namespace WebApplication1.Models

{

    public class EmployeeModel

    {

        public int EmployeeId { get; set; }

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

    }

}


In above code i have take a selectlistitem of list type and give it name employeelist. Now we will create a view .cshtml file and add the below code in it.


@model WebApplication1.Models.EmployeeModel

@{

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

}

@using (Html.BeginForm("Index", "Home", FormMethod.Post))

{

    <div class="text-left">

        @Html.DropDownListFor(m => m.EmployeeId, new SelectList(Model.EmployeeList, "Value", "Text"), new { @class = "form-control", @style = "width:50%;" })<br />

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

        <b>

            <b>Value: </b>  @ViewBag.SelectedValue<br />

            <b>Text: </b> @ViewBag.SelectedText

        </b>

    </div>

}


Now we will come to our controller and add the below code into it.


using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.Rendering;

using Microsoft.Extensions.Logging;

using System;

using System.Collections.Generic;

using WebApplication1.data;

using WebApplication1.Models;

using System.Linq;

namespace WebApplication1.Controllers

{

    public class HomeController : Controller

    {

        private readonly ILogger<HomeController> _logger;

 

        public HomeController(ILogger<HomeController> logger)

        {

            _logger = logger;

        }

        [HttpGet]

        public IActionResult Index()

        {

            EmployeeModel employeeModel = new EmployeeModel();

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

            employeeModel.EmployeeList.Add(new SelectListItem

            {

                Value = "",

                Text = "Select Employee"

            }); 

            TestDBContext testDBContext = new TestDBContext();

            var data = testDBContext.Employees;

            foreach (var item in data)

            {

                employeeModel.EmployeeList.Add(new SelectListItem

                {

                    Value = Convert.ToString(item.Id),

                    Text = item.EmployeeName

                });

            }

            return View(employeeModel);

        }

        [HttpPost]

        public IActionResult Index(EmployeeModel employeeModel)

        {

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

            employeeModel.EmployeeList.Add(new SelectListItem

            {

                Value = "",

                Text = "Select Employee"

            });

 

            TestDBContext testDBContext = new TestDBContext();

            var data = testDBContext.Employees;

            foreach (var item in data)

            {

                employeeModel.EmployeeList.Add(new SelectListItem

                {

                    Value = Convert.ToString(item.Id),

                    Text = item.EmployeeName

                });

            }

            ViewBag.SelectedValue = employeeModel.EmployeeId;

            ViewBag.SelectedText = data.Where(m => m.Id == employeeModel.EmployeeId).FirstOrDefault().EmployeeName;

            return View(employeeModel);

        }

    }

}

In above code i have created the object of the model class and the created the entity of the DBContext. After getting the employee list and added to the employee model selectlist. In this on post we are getting the selected value and on the bases of  selected value we are filtering the name. Now we have done. Run the code and check the output.



Now select the value and click on submit.



Here is the selected value of the dropdown .



Now click on submit button and check the controller end for the selected value.



Here you can see we are getting the selected value of drop down. Now we have done press F5 and check the output.


Note: You must change the connection string in DB context file. 

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

9 comments:

  1. Your means of explaining the whole thing in this post is really
    good, all be able to easily know it, Thanks a lot.

    ReplyDelete
  2. I couldn't resist commenting. Very well written!

    ReplyDelete
  3. I am regular reader, how are you everybody? This article posted at this site is really fastidious.

    ReplyDelete
  4. I’m not that much of a internet reader to be honest but your blogs really
    nice, keep it up! I'll go ahead and bookmark
    your site to come back later on. All the best

    ReplyDelete
  5. Great web site you have got here.. It's hard to find excellent writing like yours these days.
    I really appreciate individuals like you! Take care!!

    ReplyDelete
  6. Great website. A lot of helpful info here. I'm sending it to several
    buddies ans additionally sharing in delicious.
    And certainly, thanks to your effort!

    ReplyDelete
  7. Hello, yup this post is really good and I have learned lot of
    things from it regarding blogging. thanks.

    ReplyDelete
  8. I was able to find good info from your content.

    ReplyDelete
  9. I used to be able to find good information from your blog posts.

    ReplyDelete

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