Link to home
Start Free TrialLog in
Avatar of maqskywalker
maqskywalker

asked on

binding dropdownlist selected value to label in ASP.NET MVC

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:

User generated image
My project looks like this:

User generated image
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:
User generated image
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:

User generated image

Anyone know how I can fix my view so the selected value from the dropdownlist shows on the label?
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

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

Avatar of maqskywalker
maqskywalker

ASKER

My revised directory looks like this:

User generated image
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:

User generated image
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?
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial