Click here to Skip to main content
15,346,368 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I would like to have a dropdownlist in MVC4 to select all cities from database and display code on a when I select Durban it should display 031. Please help! the table looks like this:




1 solution

Im making the assumption you understand some of the basic principles of MVC, you are familiar with JQuery, have exposure to HTML Helpers in Razor.

1) Your controller. Im not making any database calls as i dont feel like throwing a database together. All you would have to do is make the call to your databse, loop over the result set and within your loop, add the contents to your List<selectlistitem>.

public class HomeController : Controller
        public ActionResult Index()
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            List<SelectListItem> list = new List<SelectListItem>();

            list.Add(new SelectListItem() { Text = "Durban", Value = "031" });
            list.Add(new SelectListItem() { Text = "Joburg", Value = "011" });

            DemoModel model = new DemoModel();
            model.ListItems = list;

            return View(model);

2. Build a model. My model only has one field for ListItems

public class DemoModel
        public List<SelectListItem> ListItems = new List<SelectListItem>();

3. Your Html.

@Html.DropDownListFor(m=>m.ListItems, Model.ListItems, "Make Selection")
<label id="dropdownlabel">Nothing Selected</label>

4. Your jquery

<script type="text/javascript">
    $(function() {
        $("#ListItems").live("change", function() {

This bit of code i did test and it does work so if you have any issues, look at how you've implemented it/any calls to your database.
AMADIAR 13-Aug-13 5:32am
Hi David,
Thank you so much for your help. It's working fine.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900