2014-09-19 82 views
2

我只是試圖添加一個默認值(「創建新的場地」)到這個列表中,它可能比我做的更容易。我被方法重載弄糊塗了,尤其是因爲我使用的(通過腳手架創建的)重載是DropDownList(字符串名稱,IEnumerable selectList,object htmlAttributes),第二個參數爲null,但它起作用。我認爲這裏有一些會議在工作。任何人都可以闡明這一點和/或我可以如何將默認值添加到此列表中?Html.DropDownList默認值MVC 5

控制器:

ViewBag.VenueId = new SelectList(db.Venues, "Id", "Name", review.VenueId); 
     return View(review); 
    } 

查看:

<div class="form-group"> 
     @Html.LabelFor(model => model.VenueId, "VenueId", htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.DropDownList("VenueId", null, htmlAttributes: new { @class = "form-control" }) 
      @Html.ValidationMessageFor(model => model.VenueId, "", new { @class = "text-danger" }) 
      <div>Don't see what you're looking for? Fear not. Just type in the name and create your review; we'll fill in the rest!</div> 
     </div> 
</div> 
+0

你想要這個值是靜態添加還是從模型? – Tushar 2014-09-19 22:35:04

+0

使用[this overload](http://msdn.microsoft.com/en-us/library/dd492256(v = vs.118).aspx)其中第三個參數是「默認空項目」。但是,你是否想將價值綁定到一個屬性? – 2014-09-19 22:36:33

+0

它可以幫助你http://stackoverflow.com/questions/25861635/mvc-best-way-to-populate-html-dropdownlist/25861739#25861739 – Tushar 2014-09-19 22:54:05

回答

1

也許你可以打破你的SelectList和插入一項呢?下面是一個例子(沒有測試出來,所以不是100%肯定它的工作原理):

控制器

// Create item list from your predefined elements 
List<SelectListItem> yourDropDownItems = new SelectList(db.Venues, "Id", "Name", review.VenueId).ToList(); 

// Create item to add to list 
SelectListItem additionalItem = new SelectListItem { Text = "Create new Venue", Value = "0" }; // I'm just making it zero, in case you want to be able to identify it in your post later 

// Specify index where you would like to add your item within the list 
int ddIndex = yourDropDownItems.Count(); // Could be 0, or place at end of your list? 

// Add item at specified location 
yourDropDownItems.Insert(ddIndex, additionalItem); 

// Send your list to the view 
ViewBag.DropDownList = yourDropDownItems; 

return View(review); 

查看

@Html.LabelFor(model => model.VenueId, new { @class = "form-control" }) 
    <div> 
     @Html.DropDownListFor(model => model.VenueId, ViewBag.DropDownList) 
     @Html.ValidationMessageFor(model => model.VenueId) 
    </div> 
</div> 

編輯:

一,你應道能夠在.DropDownListFor的最後一個參數中添加默認值,如下所示:

@Html.DropDownListFor(model => model.VenueId, ViewBag.DropDownList, "Create new Venue") 
相關問題