Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

binding dropdownlist selected value to label in ASP.NET MVC

Posted on 2015-02-18
3
Medium Priority
?
1,411 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 2000 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

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

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

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …

876 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