在 MVC 中动态绑定下拉菜单的方法

本文详细介绍了在MVC中动态绑定下拉菜单的三种方法:直接使用预定义列表项、从数据库或数组中循环读取列表项、以及从数据库中读取某表的所有列表项并进行绑定。每种方法都附有相应的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在 MVC 中动态绑定下拉菜单的方法 
1. 已知下拉菜单列表项:
在 Controller 控制器类中输入已下代码
 1 public class DemoController : Controller
 2 {
 3     public ActionResult BindDropDownList()
 4     {
 5         List<SelectListItem> select1 = new List<SelectListItem>
 6         {
 7             new SelectListItem { Text = "内容", Value = "" },
 8             new SelectListItem 
 9         };
10         
11         ViewData["select1"= new SelectList(select1, "Value""Text""此处为默认项的值");
12         
13         return View();
14     }
15 }
 
在 View 中使用
1 <%= Html.DropDownList("select1"%>
 
这种方法简单明了,也比较方便,如果不用从数据库中读取数据的话,可以采用这种方法。
 
2. 从数据库或者数组中循环读取下拉列表项 
此处省略数据库连接代码,从数据库读出的数据与字符串数组中存储的数据类似,以下就以数组为例。 
在 Controller 中控制器类中输入已下代码
 1 public class DemoController : Controller
 2 {
 3     public ActionResult BindDropDownList()
 4     {
 5         string[] texts = new string[] { """""", n };
 6         string[] values = new string[] { "1""2""3", n };
 7         
 8         List<SelectListItem> select1 = new List<SelectListItem>();
 9         
10         for (int i = 0; i < texts.Length; i++)
11         {
12             select1.Add(new SelectListItem
13             {
14                 Text = texts[i],
15                 Value = values[i]
16             });
17         };
18         
19         ViewData["select1"= new SelectList(select1, "Value""Text""此处为默认项的值");
20         
21         return View();
22     }
23 }
 
在 View 中使用 
1 <%= Html.DropDownList("select1"%>
 
其实这种方法看起来跟第1种比较类似,只是读取数据的时候,采用了一个循环的语句。 
 
3.  从数据库中读取某表的所有下拉菜单列表项
此处假设已存在 Category 类,可以通过 Category.GetList() 方法获取该表的所有分类,该表包含 ID 和 Name 两个数据列。
在 Controller 中控制器类中输入已下代码
 1 public class DemoController : Controller
 2 {
 3     public ActionResult BindDropDownList()
 4     {
 5         List<CategoryEntiry> categories = Category.GetAll();
 6         
 7         ViewData["Categories"= new SelectList(categories, "ID""Name");
 8         
 9         return View();
10     }
11 }
 
在 View 中使用
1 // 首先将 ViewData 中的数据转化为 SelectList
2 <% SelectList categories = ViewData["Categories"as SelectList; %>
3 
4 // 然后才能输出
5 <%= Html.DropDownList("Category", categories) %>
 
在这里需要注意,就是第3种与前2种在 View 中使用方法稍有不同,当然也可以将前2种方法改为第3种方法,或者将第3种方法改为前2种方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值