加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何在C#中为MVC创建值为“00”和“”的自己的Se

发布时间:2020-12-16 03:37:48 所属栏目:asp.Net 来源:网络整理
导读:我的行动中有以下代码: ViewBag.AccountId = new SelectList(_reference.Get("01") .AsEnumerable() .OrderBy(o = o.Order),"RowKey","Value","00"); 在我看来: @Html.DropDownList("AccountID",null,new { id = "AccountID" }) 现在我想动态创建列表,所以
我的行动中有以下代码:

ViewBag.AccountId = new SelectList(_reference.Get("01")
            .AsEnumerable()
            .OrderBy(o => o.Order),"RowKey","Value","00");

在我看来:

@Html.DropDownList("AccountID",null,new { id = "AccountID" })

现在我想动态创建列表,所以在我的动作中,我只想用一个简单的SelectList进行硬编码,其值为:00和“”,这样当我进入我的视图时,我只看到一个空白的选择框.

有人可以解释我如何在C#中做到这一点.

解决方法

在你的控制器中:

var references = _reference.Get("01").AsEnumerable().OrderBy(o => o.Order);

List<SelectListItem> items = references.Select(r => 
    new SelectListItem()
    {
        Value = r.RowKey,Text = r.Value
    }).ToList();

var emptyItem = new SelectListItem(){
    Value = "",Text  = "00"
};

// Adds the empty item at the top of the list
items.Insert(0,emptyItem);

ViewBag.AccountIdList = new SelectList(items);

在你看来:

@Html.DropDownList("AccountID",ViewBag.AccountIdList)

注意,不需要添加新的{id =“AccountId”},因为MVC无论如何都会给出控件ID.

编辑:

如果您只需要一个空的下拉列表,为什么要在控制器中创建一个非空的选择列表?

无论如何,这是你可以做的(视图代码保持不变):

List<SelectListItem> items = new List<SelectListItem>();

var emptyItem = new SelectListItem(){
    Value = "",Text  = "00"
};

items.Add(emptyItem);

ViewBag.AccountIdList = new SelectList(items);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读