Html.DropDownList传值

Html.DropDownList传值:
  可以传入明确的IEnumerable<SelectListItem>,也可以通过ViewBag或者ViewData隐式地传入,前提是需要相同的名称,比如:ViewBag.GenreId或者ViewData["GenreId"]。
示例:

public ActionResult Index()
{
    var SelectItems = new List<dynamic>(){
        new { id = 1, name="刘新"},
        new { id = 2, name="小明"},
        new { id = 3, name="蛋蛋"}
    };
    //SelectList : 使用SelectList辅助类构建
    ViewBag.SelectItem = new SelectList(SelectItems, "id", "name", 2);
    
    //使用SelectListItem对象集合
    var SexItems = new List<SelectListItem>{
        new SelectListItem{ Text="", Value="1", Selected=true},
        new SelectListItem{ Text="", Value="0"}
    };
    return View(SexItems);
}

 

视图:

@model IEnumerable<System.Web.Mvc.SelectListItem>
//使用ViewBag或者ViewDate隐式传入,通过@Html.DropDownList指定的name匹配ViewBag或者ViewDate的属性值(不指定第二个参数默认是根据指定的name去ViewBag或者ViewData查找同名的属性)
@Html.Label("person_id", "人员"): @Html.DropDownList("SelectItem", null, new { id = "person_id" })<br/>
//也可以将ViewBag.SelectItem转换成IEnumerable<SelectListItem>
@Html.Label("person_id", "人员"): @Html.DropDownList("SelectItem", ViewBag.SelectItem as IEnumerable<SelectListItem>, new { id = "person_id" })<br/>
//使用强类型视图对象填充select, 需要声明Model的类型
@Html.Label("sex", "性别"): @Html.DropDownList("sex", Model, new { id = "sex" })

注意:
1. @Html.Label的第一个参数表示for特性的值, 第二个参数表示lable文本
2. SelectList是IEnumerable<SelectListItem>的进一步封装而已。可以根据不同的场景选择使用哪一种
3. 将SelectList转换成IEnumerable<SelectListItem>会丢失默认选择的项
执行结果:

生成的代码:

<label for="person_id">人员</label>: 
    <select id="person_id" name="SelectItem">
        <option value="1">刘新</option>
        <option selected="selected" value="2">小明</option>
        <option value="3">蛋蛋</option>
    </select>
<br/>
<label for="person_id">人员</label>: 
    <select id="person_id" name="SelectItem">
        <option value="1">刘新</option>
        <option value="2">小明</option>
        <option value="3">蛋蛋</option>
    </select>
<br />
<label for="sex">性别</label>: 
    <select id="sex" name="sex">
        <option selected="selected" value="1"></option>
        <option value="0"></option>
</select>

 




转载于:https://www.cnblogs.com/enfp/p/7718345.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值