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




City
Code

Durban
031

Joburg
011
Posted

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>.

C#
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

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



3. Your Html.

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


4. Your jquery

XML
<script type="text/javascript">
    $(function() {
        $("#ListItems").live("change", function() {
            $("#dropdownlabel").text($(this).val());
        });
    });
</script>




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.
 
Share this answer
 
Comments
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