Solved

binding dropdownlist selected value to label in ASP.NET MVC

Posted on 2015-02-18
3
936 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
  • 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

867 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now