Solved

binding dropdownlist selected value to label in ASP.NET MVC

Posted on 2015-02-18
3
1,260 Views
Last Modified: 2015-02-20
Hi experts,

I'm using Visual Studio 2013 and sql server 2008.
I created a empty ASP.NET MVC application.
I'm using the Database First Entity model.
I'm using the Employees table from the Northwind database.

So I created my entity model for my Employees table and it looks like this:

entity model
My project looks like this:

my directory
This is the code for my controller HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SampleApp1.Models;

namespace SampleApp1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            NorthwindEntities db = new NorthwindEntities();

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

            return View();
        }

    }
}

Open in new window


This is the code for my view Index.cshtml

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

Select Employee: @Html.DropDownList("Employees", "Select Employee")

<br/> <br />
You selected: @ViewBag.LastName

Open in new window


When I run my page my dropdown list is filled with the correct data and it looks like this:
my dropdown list filled with data
What I'm trying to do is bind whatever name I pick from the dropdownlist and show it in a label.

So with my code above, when I select a name from the dropdownlist nothing is showing in the label.

So for example, if I picked Davolio from the drop down list then my page should look like this:

my desired result

Anyone know how I can fix my view so the selected value from the dropdownlist shows on the label?
0
Comment
Question by:maqskywalker
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40619754
1) Set the drop-down list to auto-post back.

Example:

@Html.DropDownList("qchap", new SelectList( (IEnumerable)ViewData["qchap"], "Id", "Title" ), new { onchange = "this.form.submit();" })

2) Add a form action, using Html.BeginForm.

Example:

@using (Html.BeginForm("Login", "Account"))
{
    @Html.TextBox("Name");
    @Html.Password("Password");
    <input type="submit" value="Sign In">
}

3) Add a property to the view model for selected employee.

4) In the form action (Account/Login in the above example), set the model property.

5) Add a controller method with an [HttpPost] attribute to handle the submit action.

Example:

public class Account
{

   [HttpPost]
   public void Login() 
  {
  }

}

Open in new window

0
 
LVL 1

Author Comment

by:maqskywalker
ID: 40621636
My revised directory looks like this:

revised project directory
Model

EmployeeModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SampleApp1.Models
{
    public class EmployeeModel
    {
        public SelectList EmployeeListModel { get; set; }
    }
}

Open in new window



Controller

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SampleApp1.Models;

namespace SampleApp1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            // Create instance of entity model
            NorthwindEntities objentity = new NorthwindEntities();

            // create object list
            List<Employee> objemployeelist = (from data in objentity.Employees
                                              select data).ToList();
            // create employee object
            Employee objemployee = new Employee();
            // set employee object properties
            objemployee.LastName = "Select";
            objemployee.EmployeeID = 0;
            objemployeelist.Insert(0, objemployee);

            // create list from employee objects
            SelectList objmodeldata = new SelectList(objemployeelist, "EmployeeID", "LastName", 0);

            // Assign value to model
            EmployeeModel objemployeemodel = new EmployeeModel();
            objemployeemodel.EmployeeListModel = objmodeldata;

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

            // controller returns model to view
            return View(objemployeemodel);
        }

        [HttpPost]
        public ActionResult Index(int ddlemployee)
        {
            // Create instance of entity model
            NorthwindEntities objentity = new NorthwindEntities();

            // create object list
            List<Employee> objemployeelist = (from data in objentity.Employees
                                              select data).ToList();
            // create employee object
            Employee objemployee = new Employee();
            // set employee object properties
            objemployee.LastName = "Select";
            objemployee.EmployeeID = 0;
            objemployeelist.Insert(0, objemployee);

            // create list from employee objects
            SelectList objmodeldata = new SelectList(objemployeelist, "EmployeeID", "LastName", 0);

            // Assign value to model
            EmployeeModel objemployeemodel = new EmployeeModel();
            objemployeemodel.EmployeeListModel = objmodeldata;

            /*************** Get the selected Employee ***************/
            ViewBag.LastName = objemployeelist.Where(m => m.EmployeeID == ddlemployee).FirstOrDefault().LastName;
            /*************** Get the selected Employee ***************/

            return View(objemployeemodel);
        }

    }
}

Open in new window



View

Index.cshtml

@model SampleApp1.Models.EmployeeModel

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


@*Select Employee: @Html.DropDownList("Employees", "Select Employee")*@


@using (Html.BeginForm("Index", "Home"))
{
    <style type="text/css">
        .Title1 {
            font-family: Arial;
            font-size: 14px;
            font-weight: bold;
            color: #000000;
        }

        .Label1Text {
            font-family: Arial;
            font-size: 12px;
            font-weight: normal;
            color: #000000;
        }

        .Value1Text {
            font-family: Arial;
            font-size: 12px;
            font-weight: bold;
            color: #0000ff;
        }
    </style>

    <h2 class="Title1">
        Bind Entity Model to DrowpDownList and pass selected value onchange
    </h2>
    @*@Html.DropDownList("ddlemployee", Model.EmployeeListModel, new { @style = "width:200px;" })*@
    @*<input type="submit" value="Submit" />*@

    @Html.DropDownList("ddlemployee", Model.EmployeeListModel, new { onchange = "this.form.submit();" })

    <br />
    <div>
        <span class="Label1Text">Selected Employee: </span><span class="Value1Text">@ViewBag.LastName</span>
    </div>
}

Open in new window


When I run my page it works fine and looks like this:

my working drop down using onchange event instead of button click event
You can download the Visual Studio 2013 Project by click this link

Just change the connection string in the web.config to your northwind database on your sql server and run.


Is the the best way to bind this mvc drop down ?
or
Is there a more elegant way with less code?
Is it better to use IEnumerable instead?
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 40621674
While I answered the question that you posed, I am curious what value the label provides.  It basically mimics that value in the drop-down.  I would think that the label would be better used to show a different value than is shown in the text.

Example:

OH

Selected state:  Ohio

       or

Davolio

Selected Employee ID:  64010

1) Is the the best way to bind this mvc drop down?
For me "Best is unattainable", I will only suggest better, since my knowledge may be limited.  Also, I am not sure what improvement you would be looking for.

2) Is there a more elegant way with less code?
Less code where?  Are you looking for less database code?  Entity framework?  NHibernate?

3) Is it better to use IEnumerable instead?
Are you talking about something like this?

DropDownListFor with ASP.NET MVC
http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx

 public IEnumerable<SelectListItem> FlavorItems
    {
        get { return new SelectList(_flavors, "Id", "Name");}
    }

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

628 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question