2016-09-29 53 views
0

基于此代码(自动生成的控制/查看从Visual Studio代码)字符串的显示列表:MVC - 在DropDownList中

<div class="form-group"> 
    @Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @*Comment: Want to replace EditorFor to DropDownList("Banana, "Apple", "Orange"*@ 
     @Html.EditorFor(model => model.Type, new { htmlAttributes = new { @class = "form-control" } })*@ 
     @Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" }) 
    </div> 
</div> 

我想补充相似喜欢的东西:

@Html.DropDownList("UserId", null, htmlAttributes: new { @class = "form-control" }) 
代替 @html.EditorFor...

(也自动生成的代码,但对于UserId)我能看到的UserName列表(值= Id)的F通过控制器ROM DB:

ViewBag.UserId = new SelectList(db.Users, "Id", "UserName", Test.UserId); 

现在,我不希望这样ViewBag从数据库中读取,而不是我希望它列出我将用它来让用户选择了INDATA(意思3个不同的字符串,限制他们选择这3个字符串中的一个来代替它)。

字符串我希望它列出:

  • “香蕉”
  • “苹果”
  • “橙色”

我该怎么办呢?

回答

1

试试这个做的另一种方式,

@Html.DropDownList("DropDown", new List<SelectListItem> 
           { new SelectListItem { Text = "Banana", Value = "1", Selected=true}, 
            new SelectListItem { Text = "Apple", Value = "2"}, 
            new SelectListItem { Text = "Orange", Value = "3"} 
            }, "Select Fruit") 

0123在模型

获得价值

@Html.DropDownListFor(x => x.Id, new List<SelectListItem> 
           { new SelectListItem { Text = "Banana", Value = "1", Selected=true}, 
            new SelectListItem { Text = "Apple", Value = "2"}, 
            new SelectListItem { Text = "Orange", Value = "3"} 
            }, "Select Fruit") 
+0

感谢它运作良好!只是一个问题,这在工作领域仍然是一种正确的方式(例如平均安全性)还是应该考虑其他解决方案? – Nyprez

+0

@Nyprez是的,两者都是正确的方式。如果您希望模型中的选定值比首先使用第二个选项更有用。 –

0

只需将您指定的内容更改为ViewBag.UserId即可。像这样:

var fruits = new List<string> { "Banana", "Apple", "Orange" }; 
ViewBag.Fruits = fruits.Select(f => new SelectListItem { Text = f, Value = f }); 
+0

使用'@ Html.DropDownList( “水果”,空,htmlAttributes:新{@class = “表单控制”})'在查看了我的错误:'有是没有类型为'IEnumerable '的ViewData项目,其具有关键字'Fruits'.'。我究竟做错了什么? – Nyprez

+0

作为第二个参数,你必须像这样传递ViewBag.Fruits: '@ Html.DropDownList(“Fruits”,ViewBag.Fruits,htmlAttributes:new {@class =“form-control”})' –

0

这是你如何建立你的列表项:

ViewBag.Fruits = new SelectList(
    new List<SelectListItem> 
    { 
     new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"}, 
     new SelectListItem { Selected = false, Text = "Banana", Value = 0}, 
     new SelectListItem { Selected = false, Text = "Apple", Value = 1}, 
    }, "Value" , "Text", 1); 
+0

尝试调用它在视图中:'@ Html.DropDownList(“Fruits”,null,htmlAttributes:new {@class =“form-control”})'但是我得到错误:'没有ViewData项的类型为'IEnumerable '有'水果'这个关键字。' – Nyprez

0

下面是使用枚举

public enum Fruit { Banana, Apple, Orange } 

@Html.DropDownList("FruitSelection", 
        new SelectList(Enum.GetValues(typeof(Fruit))), 
        "Select Fruit", 
        new { @class = "form-control" }) 
+0

在控制器中添加'public enum Fruit'吗?如果我这样做,我会收到错误“不能解析符号'水果'”,另外还有3个错误。 – Nyprez