2014-04-04 37 views
0

我有我的觀點一個DDL,我從DB這樣的閱讀DDL的項目和值:在DDL(MVC4)設置的第一項的值設置爲null

  ViewBag.ContentGroup = new SelectList(obj.GetContentGrouplist(), "Id", "Name"); 

我把它放在viewbag和我讀到這樣從視圖中viewbag:

<div class="editor-label"> 
      @Html.LabelFor(model => model.ContentGroupFKId) 
     </div> 
     <div class="editor-field"> 
      @Html.DropDownListFor(x => x.ContentGroupFKId, (SelectList)ViewBag.ContentGroup) 
      @Html.ValidationMessageFor(model => model.ContentGroupFKId) 
     </div> 

所以我需要的是,第一項爲空我怎麼做一個DDL?

我試過,但它不工作:

  @Html.DropDownListFor(x => x.ContentGroupFKId,new SelectList(new List<Object> {new {value = null, text = "Select"} (SelectList)ViewBag.ContentGroup) 

最好的問候。

回答

1

我不認爲你可以。無論您提供什麼值,都將用於以選擇列表的形式生成html,該列表不支持null。只要你有一個DropDownListFor,它將設置一個值,即使它是空的。您可以做的最好的事情是將第一個值設爲「請選擇一個項目」選項並將其設置爲空服務器端。

沒有添加「請選擇」選項,一個偉大的方式(至少沒有我所看到的。人們歡迎大家指正雖然!),但也有一些方法來做到這一點。其中一個就是創建一個只有名稱和ID的虛擬內容組。

var contentGroups = obj.GetContentGrouplist(); 
contentGroups.Insert(0, new ContentGroup{Id = "0", Name = "Please select a content group"}; 
ViewBag.ContentGroup = new SelectList(contentGroups, "Id", "Name"); 

或者你可以創建一個對象(你會在任何地方使用,你需要這個功能),只是持有的文本和值屬性,然後手動將所有內容組添加到它,包括空單。

class DropDownListOption{ 
    public string Text{get;set;} 
    public string Value{get;set;} 
} 

然後在你的代碼

var contentGroups = obj.GetContentGrouplist(); 
var options = new List<DropDownListOption>(); 

options.Add(new DropDownListOption{ Id = "0", Text = "Please select a content group"}; 

foreach(var group in contentGroups) 
{ 
    options.Add(new DropDownListOption{ Id = group.Id, Text = group.Name}; 
} 

ViewBag.ContentGroup = new SelectList(options, "Id", "Name"); 

這兩個選項將工作。我更喜歡第二種選擇,因爲您可以創建一種以某種方式處理所有下拉列表的通用方法。當用戶提交表單時,您必須處理ID爲0的ContentGroups爲null,但至少它是一種跟蹤它的方式。

如果我想別的辦法生病添加。

+0

所以,我該怎麼辦呢?我的意思是「‘請選擇一個項目’ –

+0

增加了一些細節 – bsayegh

+0

謝謝@ bsayegh –