Solved

binding dropdownlist selected value to label in ASP.NET MVC

Posted on 2015-02-18
3
884 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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

762 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

9 Experts available now in Live!

Get 1:1 Help Now