asp.net mvc dropdownlist selected values

Hi experts,

I have a ASP.NET MVC 5, C#, Razor application.
I'm using Sql Server 2008, Entity Framework 6, Database First Model.
For my example i'm using the Employees table from the Northwind Sql Server database.

The employee table looks like this:

Northwind Employees sql server table
So I have a basic mvc application. I created a model called Northwind.edmx which contains my Employees model.

So my application directory looks like this:
Asp.net mvc application directory
So this is my I currently have:

Controller

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using NorthwindApp.Models;

namespace NorthwindApp.Controllers
{
    public class HomeController : Controller
    {
        // ******************* Bind Employees table to DDL using ViewBag *******************

        // GET: Home
        public ActionResult Index()
        {
            NorthwindEntities db = new NorthwindEntities();

            ViewBag.Employees = new SelectList(db.Employees, "EmployeeID", "LastName", "FirstName");

            return View(db.Employees.ToList());
        }
        
        // ******************* Bind Employees table to DDL using ViewBag *******************

    }
}

Open in new window



View


Index.cshtml


@model IEnumerable<NorthwindApp.Models.Employee>

@{
    ViewBag.Title = "Index";
}
<style type="text/css">
    .DDLValueText{
        color: #ff0000;
    }
</style>
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {
        // ------------------------------

        // change event function for the DropDownList with id of FruitDDL
        $('#EmployeesDDL').change(function (e) {
            
            // set selection value of ddl with id of EmployeesDDL to a variable called selected_Value
            var selected_value = document.getElementById("EmployeesDDL").value;

            document.getElementById("demo1").innerHTML = "The item you selected is: " + "<span class='DDLValueText'>" + selected_value + "</span>";

        });
        
        // ------------------------------
        // end of document ready function
    });

</script>


<table>
    <tr>
        <td></td>
        <td>Select Employee:</td>
        <td></td>
        <td>
            @*@Html.DropDownList("Employees", "Select Employee")*@
            @Html.DropDownList("EmployeesDDL", (IEnumerable<SelectListItem>)ViewBag.Employees, "Select Employee", new { @class = "form-control" })
        </td>
    </tr>
</table>
<br /><br /><br /><br />

<p id="demo1"></p>

Open in new window


So then when I run my app on my page I have a dropdownlist that looks like this:

when i run page
So now if I click on the dropdownlist I see all the lastnames in the dropdownlist like this:

when i click on dropdownlist
When I select one of the last names,
for example if I select Peacock then the selected value for the EmployeeID pertaining to Peacock displays on the page like this:

after I selected an item from the dropdownlist

So what's going on is, the dropdownlist is showing the last names but when I pick an item the selected value is actually picking the EmployeeID column of my model.

How do I revise my example so that aside from displaying the selected value as it is doing now,
I also want to show the LastName and FirstName on my page.

So then after I select an item from my dropdownlist on my page it will display this:

desired display on my page
Anyone know how I can save the lastname and firstname of the item i selected from the dropdown and save it to a variable so i can them display those on my screen?
LVL 1
maqskywalkerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bob LearnedCommented:
Here is my suggestion approach using the Adventure Works database:

1. Index View



@model IEnumerable<SelectListItem>

@{
    ViewBag.Title = "Home Page";
}

@Html.DropDownList("Employees", @Model, "Select Employee", new { @class = "form-control" })

<br />
<br />

<script type="text/javascript">

    $(document).ready(function () {
        // ------------------------------

        $('#Employees').change(function (e) {

            var employeeId = $(this).val();

            var url = '/home/findEmployee/' + employeeId;

            $.ajax({
                url: url,
                dataType: "json",
                type: "GET",
                success: function (data) {
                    alert(data.FirstName + " " + data.LastName);
                },
                error: function (xhr) {
                    alert('error: ' + xhr.responseText);
                }
            });
        });

    });

</script>

Open in new window


2. Index Controller Method



   
public ActionResult Index()
        {
            var employeeList = _dataContext.Employees
                .Select(x => new SelectListItem { Text = x.Person.LastName + ", " + x.Person.FirstName, Value = x.Person.BusinessEntityID.ToString() })
                .OrderBy(x => x.Text);

            return View(employeeList);
        }

Open in new window



3. Add Controller Method to Return JSON Object



Add a FindEmployee method to get the employee by ID:

  [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult FindEmployee(int? id)
        {
            var employee = _dataContext.Employees
                .Select(x => x.Person)
                .FirstOrDefault(x => x.BusinessEntityID == id);

            if (employee == null)
                throw new NullReferenceException("Unable to find employee by ID " + id);

            return Json(employee, JsonRequestBehavior.AllowGet);
        }

Open in new window


maqskywalkerAuthor Commented:
Do you know which version of the AdventureWorks sql server database you are using?
Bob LearnedCommented:
I am using the AdventureWorks2014 database for SQL Server 2014.

Adventure Works 2014 Sample Databases
https://msftdbprodsamples.codeplex.com/releases/view/125550

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.