2012-01-18 16 views
0

ちょっと友人私は私のmvc 3プロジェクトでドロップダウンリストを使用しています。ここで、ユーザーはオプションの1つを選択して保存します。そして、私が最初に保存した値を選択した値にする必要がある以上、彼/彼女がページを再訪するとき。実際に私は、必要に応じてカスタムHTMLヘルパーでこれをやっています。しかし、私はそれに問題を抱えています。私はこれをやっている:実際のコードの上にmvcのドロップダウンリスト3

else if (question_type == 7) 
     { 
      EAI.DAL.EaiEntities entities = new DAL.EaiEntities(); 
      QuestionnaireRepository repository = new QuestionnaireRepository(entities); 
      SelectList typesList = repository.PopDdlList(qid);     


      output.Append(helper.Label(questiontext)); 
      if (answer == "") 
      { 
       output.Append(helper.DropDownList("ddl" + question_id, typesList, "-- select type----)); 

      } 
      else 
      { 
       output.Append(helper.DropDownList("ddl" + question_id, typesList, answer)); 

      } 


      return helper.Raw(output.ToString()); 
     } 

データベースから選択した値をレンダリングするが、それは実際に置き換える「 - ---選択タイプ」。だから、もし私が同じページを訪問し、私はFormcollectionで空の値を取得することができますよりもページを保存すると一度保存した後。

ので、やっての適切な方法を提案してください。この

答えて

1
私は通常私のモデルにいくつかのプロパティを追加

int SelectedCategory { get; set; } 

IEnumerable<SelectListItem> Categories { get; private set; } 

、その後、私のモデルのコンストラクタでデータをロード:

ProductService productService = new ProductService(); 

this.Categories = 
    productService.GetCategories() 
     .Select(c => new SelectListItem() { Text = c.Name, Id = c.Id.ToString() }); 

this.Categories.InsertAt(0, new SelectListItem() { Text = "--- Please Select ---", value = "" }); 

私のRazorのマークアップでは、次のようなコードを入力してください。

@Html.DropDownListFor(m => m.SelectedCategory, Model.Categories) 

これは、標準MVCの方法で自動ワイヤーアップする必要があります。お役に立てれば。

関連する問題