如何创建具有"00"值的我自己的SelectList?和“"在C#中使用MVC? [英] How can I create my own SelectList with values of "00" and "" in C# for MVC?

查看:37
本文介绍了如何创建具有"00"值的我自己的SelectList?和“"在C#中使用MVC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的操作中包含以下代码:

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

在我看来:

  @ Html.DropDownList("AccountID",空,新的{id ="AccountID"}) 

现在,我想动态创建列表,因此在我的操作中,我想用值00和"对一个简单的SelectList进行硬编码,这样当我进入视图时,只会看到一个空白的选择框./p>

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

解决方案

在您的控制器中:

  var引用= _reference.Get("01").AsEnumerable().OrderBy(o =&>; o.Order);List< SelectListItem>items =引用.Select(r =>新的SelectListItem(){值= r.RowKey,文字= r.Value}).ToList();var emptyItem = new SelectListItem(){值=",文字="00"};//将空项目添加到列表顶部items.Insert(0,emptyItem);ViewBag.AccountIdList = new SelectList(items); 

您认为:

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

注意,无需添加 new {id ="AccountId"} ,因为MVC仍会为控件提供该ID.

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

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

  List< SelectListItem>items = new List< SelectListItem>();var emptyItem = new SelectListItem(){值=",文字="00"};items.Add(emptyItem);ViewBag.AccountIdList = new SelectList(items); 

I have the following code in my action:

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

and in my view:

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

Now I would like to create the list dynamically so in my action I would just like to hardcode a simple SelectList with the values: 00 and "" so that when I go to my view I see just a blank select box.

Can someone explain how I can do this in C#.

解决方案

In your controller:

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);

In your view:

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

Note, no need to add new { id = "AccountId" } since MVC will give the control that ID anyway.

Edit:

If you only need an empty drop down list why are you creating a select list that isn't empty in your controller?

Anyway, here's what you can do (the view code remains the same):

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

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

items.Add(emptyItem);

ViewBag.AccountIdList = new SelectList(items);

这篇关于如何创建具有"00"值的我自己的SelectList?和“"在C#中使用MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆