ドロップダウンの最初の引数と 2 番目の引数と同じ名前を使用しないでください。あなたの例ではproductType
、選択した値と使用可能な値のリストの両方を保存するために使用しました。ASP.NET MVC でドロップダウンをレンダリングするには、次の 2 つのプロパティが必要です。
<%= Html.DropDownList(
"selectedProductType",
ViewData["productType"] as SelectList,
"defaultValue"
) %>
コントローラー アクション内で、これら 2 つのプロパティを設定できます。
ViewData["selectedProductType"] = "abc";
ViewData["productType"] = new SelectList(myDropDownList);
value="abc"
これは、製品タイプのドロップダウン リスト内に既に要素があることを前提としています。値は自動的に事前選択されます。
ドロップダウンリストをレンダリングするための別のアプローチをお勧めします。これは、ビュー データを取り除き、ビュー モデルを導入し、強く型付けされたバージョンのヘルパーを使用することで構成されます。
public class ProductViewModel
{
public string SelectedProductType { get; set; }
public IEnumerable<SelectListItem> ProductTypes { get; set; }
}
次に、このビュー モデルにデータを入力してビューに渡すコントローラー アクションが作成されます。
public ActionResult SomeAction()
{
var model = new ProductViewModel();
// preselected an element with value = "type2"
model.SelectedProductType = "type2";
// bind the available product types
model.ProductTypes = new SelectList(
// Obviously those could come from a database or something
new[] {
new { Value = "type1", Text = "product type 1" },
new { Value = "type2", Text = "product type 2" },
new { Value = "type3", Text = "product type 3" },
new { Value = "type4", Text = "product type 4" },
},
"Value",
"Text"
);
// pass the view model to the view
return View(model);
}
最後に、強く型付けされたビュー内:
<%= Html.DropDownListFor(
x => x.SelectedProductType,
Model.ProductTypes,
"defaultValue"
) %>