2012-03-12 20 views
0

我有以下操作方法發起的SelectList如下: -我怎麼可以動態地添加一個新的實體,以我的Htmlhelper.dropdownlist

 public PartialViewResult Search(string q, int q2,string q3,string sortOrder) 
    { 

    ViewBag.q2 = new SelectList(elearningrepository.FindAllLevels().ToList(), "DifficultyID", "Description", 2); 
    ViewBag.q3 = new SelectList(elearningrepository.FindAllusers().ToList(), "UserID", "UserID",2); 
    ViewBag.today = DateTime.Today; 
    ViewBag.nextmonth = DateTime.Now.AddMonths(1); 
    var v = elearningrepository.searchquestions3(q, q2, q3); 
    return PartialView("_searchquestion", v); 
     } 

而下面的倉庫方法: -

public IQueryable<Question> searchquestions3(string q, int? q2 , string) 
      { 

    return from u in entities1.Questions 
    where (u.Description.Contains(q) && (u.DifficultyID == q2 || q2 == "Any") && (u.CreatedBy == q3 || q3 == "Any"))       
select u;} 

然後在視圖上我呈現下拉列表如下: -

<th> 
@Html.DropDownList("q2")   
</th> 
</tr> 
    <tr> 
<th> 
Seach By Create By:- 
</th> 
<th> 
@Html.DropDownList("q3") 
</th> 

但是ho w我可以添加一個表示「Any」字的新值到q2下拉列表中,以便存儲庫方法能夠按預期工作? BR

回答

2

首先,我會建議你在使用更復雜的對象時使用ViewModels。當然你可以用ViewBag來實現它,但是很麻煩。

現在。在操作,你可以這樣做:

var list = elearningrepository.FindAllLevels().ToList() 
list.InsertAt(0, new TypeOfYourObject() {ValueProperty = "Any"}); 
ViewBag.q2 = new SelectList(list, "DifficultyID", "Description", 2); 

您可以與其他adequatly做的,但認真想想強類型的視圖模型。使用jQuery

$("#Select_Id").append("<option value='0'>Text</option>"); 

您可以使用.prepend(),如果你想將其添加爲第一要素

0
@Html.DropDownList("q3","Any") 

您需要使用optionLabel

在你的控制器,你得到您的文章。

無論你想做什麼,例如。一個數據庫事務,只有當值==空字符串或標籤==「任何」

+0

但任何將被插入作爲一個標籤沒有任何價值的ID ... – 2012-03-12 14:24:04

+0

感謝您的回覆,,但你的意思是「你不能然後在你的控制器使用條件,如果你的optionLabel == 「任何」然後做一些獨特的? 「 – 2012-03-12 14:27:42

0

客戶端解決方案。

+0

這將不會插入下拉ist值,而是它會顯示在列表旁邊的值.. – 2012-03-12 15:01:52

+0

請仔細閱讀我的答案,如果您使用」prepend「它會插入爲頂部元素。例如:http://jsfiddle.net/B9BLF/1/ – 2012-03-12 19:49:45