MVC4中的下拉列表

问题描述:



我想在MVC4中有一个下拉列表,从数据库中选择所有城市并在label.eg上显示代码。当我选择德班时它应该显示031.请帮忙!表格如下:









City
代码



Durban
031



Joburg
011

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

我假设您了解MVC的一些基本原理,你熟悉JQuery,在Razor中接触过HTML Helpers。



1)你的控制器。我没有进行任何数据库调用,因为我不想把数据库放在一起。您所要做的就是调用数据库,循环结果集并在循环中,将内容添加到List< selectlistitem&gt ;.



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.建立模型。我的模型只有一个ListItems字段





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

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







3.你的Html。






3. Your Html.

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





4.你的jquery





4. Your jquery

<script type="text/javascript">


(function(){
(function() {


(#ListItems )。李ve(change,function(){
("#ListItems").live("change", function() {