2012-03-12 2 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> 

しかし、ホq2 & q3ドロップダウンリストに「Any」という単語を表す新しい値を追加すると、リポジトリメソッドは意図したとおりに動作しますか?あなたはあなたのポストを取得し、あなたのコントローラにoptionLabel

を使用する必要が 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行うことができますが、真剣程度強く型付けされたViewModelに思います。 jQueryの

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

あなたが最初の要素として追加したい場合は、().prepend使用することができると

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

あなたがしたいことは何でも、例です。データベースのトランザクションは、値==空の文字列またはラベル== "Any"の場合にのみ行われます

+0

ですが、AnyはIDの値なしでラベルとして挿入されます... –

+0

yuor replyに感謝しますが、「あなたのoptionLabel == "Any"はユニークな何かをしますか? " –

0

クライアントサイドのソリューション。

+0

これはドロップダウンistの中に値を挿入するのではなく、リストの横に値を表示します。 –

+0

" prepend "を使用する場合は、上の要素として挿入します。例:http://jsfiddle.net/B9BLF/1/ –

関連する問題