2016-03-02 48 views
5

私はデータを正しくバインドしていると信じていますが、各SelectListItemのテキストプロパティを正しく表示することができません。DropDownListに "System.Web.Mvc.SelectListItem"が表示されるのはなぜですか?

マイモデル:

public class Licenses 
    { 
     public SelectList LicenseNames { get; set; } 
     public string SelectedLicenseName { get; set; } 
    } 

コントローラー:

[HttpGet] 
    public ActionResult License() 
    { 
     try 
     { 
      DataTable LicsTable = BW.SQLServer.Table("GetLicenses", ConfigurationManager.ConnectionStrings["ProfressionalActivitiesConnection"].ToString()); 
      ProfessionalActivities.Models.Licenses model = new ProfessionalActivities.Models.Licenses(); 
      model.LicenseNames = new SelectList(LicsTable.AsEnumerable().Select(row => 
      new SelectListItem 
      { 
       Value = row["Description"].ToString(), 
       Text = "test" 
      })); 
      return PartialView("_AddLicense", model); 
     } 
     catch (Exception ex) 
     { 
      var t = ex; 
      return PartialView("_AddLicense"); 
     } 
    } 

ビュー:

@Html.DropDownList("LicenseNames", new SelectList(Model.LicenseNames, "Value", "Text", Model.LicenseNames.SelectedValue), new { htmlAttributes = new { @class = "form-control focusMe" } }) 
+1

は、DropDownListの 'の第二パラメータは()' 'のIEnumerable 'であることに注意してください。あなたはそれを 'new SelectListItem {Value = row [" Description "]。ToString()、Text =" test "})'を使って作成します。 'New SelectList()'(ここで 'Text'と' Value'プロパティを設定するのを忘れた)を使って2番目のものを作成し、3番目のものをビューに作成するのは無意味な余分なオーバーヘッドです。 –

答えて

7

タイプのSelectList

あるご LicenseNames財産の Itemsプロパティを使用します
@Html.DropDownList("SelectedLicenseName", new SelectList(Model.LicenseNames.Items, 
             "Value", "Text", Model.LicenseNames.SelectedValue)) 

またはDropDownListForヘルパーメソッドと

@Html.DropDownListFor(d=>d.SelectedLicenseName, 
             Model.LicenseNames.Items as List<SelectListItem>) 

あなたがフォームを投稿するときだから、あなたはSelectedLicenseNameプロパティ

[HttpPost] 
public ActionResult Create(Licenses model) 
{ 
    //check model.SelectedLicenseName 
} 
+0

それはうまく動作します。今、私がPOST時にSelectListから選択した値をSelectedLicenseNameプロパティに割り当てる方法を教えてください。 – JzInqXc9Dg

+0

私の更新された回答を参照してください。フォーム要素の名前を "SelectedLicenseName"として使用し、フォームが投稿されたときにその名前を読み取る必要があります。 – Shyju

+0

2番目のオプション - DropDownListFormのオプションを使用すると、最初に部分ビューを呼び出そうとするとこのエラーが発生します。 追加情報:キー「SelectedLicenseName」を持っている「のIEnumerable 」タイプの一切のViewData項目はありません。 – JzInqXc9Dg

0

を検査することができ、私は明示的にdataValueFielddataTextField名を設定します。

new SelectListItem 
{ 
    Value = row["Description"].ToString(), 
    Text = "test" 
}), "Value", "Text"); 

その後(ご受け入れ答えで提案されているように)あなたの意見にModel.LicenseNames.Items as List<SelectListItem>を記述する必要はありません。 Shyjuの答えに加えて

関連する問題