2016-09-29 71 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