コントローラでは動作しません:編集Html.DropDownListと@class属性
ViewBag.Category = new SelectList(this.service.GetAllCategories(), product.Category);
私は、ID +名を使用していませんよ。 GetAllCategories()はいくつかのint値だけを返します。
私はビューで使用します。
@Html.DropDownList("Category", String.Empty)
すべてが動作します。編集はOKで、DropDownListは選択した値を表示します。 HTML結果:
<select id="Category" name="Category">
<option value=""></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option selected="selected">5</option>
...
</select>
しかし、私はCSSを使用する必要が@classので、私はこのコードを使用:
@Html.DropDownList("Category", (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" })
HTML結果:
<select class="anything" id="Category" name="Category">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
...
</select>
残念ながら、編集はまだ私ができる(作品私が選択した値を保存します)、DropDownListはデータベースに保存された値ではなく、デフォルト値を表示し始めます。
あなたは何か問題があると思いますか?
更新 もっと正確になるように更新しました。
方法GetAllCategoriesは次のようになります。私はあなたのテーブルから考える
public List<int> GetAllCategories()
{
List<int> categories = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
return categories;
}
あなたは男です。私は完全にnull可能性を見過ごした(それは "コードブレンドネス"のようなものでなければならない;-)。 @ Html.DropDownList( "Category"、null、new {@class = "anything"})は問題を解決します。 – nubm