本文介绍了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 |
推荐答案
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">
这篇关于MVC4中的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!