Good Day everyone。 次の質問があります。DropDownListデータベースからの値に基づく選択値。
私はDropDownListコントロールがほとんどない編集フォームを持っています。 私は自分のdbにあるデータに基づいて、DropDownListForで選択した値をバインドする必要があります。
私は何を持っていることは次である:
モデル:配達編集画面用
サプライヤー
public class Supplier{
public int SupplierID { get; set; }
public string CompanyName { get; set; }
}
Delviery
public class Delivery{
public int DeliveryID { get; set; }
public string DeliveryCode { get; set; }
public int SupplierID { get; set; }
public virtual Supplier Supplier { get; set; }
}
のViewModel:
public class DeliveryEditViewModel{
public int DeliveryID { get; set; }
public string SelectedCompanyName { get; set; }
public IEnumerable<SelectListItem> Suppliers { get; set; }
}
ビュー:
<dd>
@Html.DropDownListFor(x => x.SelectedCompanyName, new SelectList(Model.Suppliers, "Value", "Text"), htmlAttributes: new { @class = "form-control" })
</dd>
コントローラ:私はドロップダウンコントロールを持っている
// GET: Deliveries/Edit
public ActionResult Edit(int? id){
db.Configuration.ProxyCreationEnabled = false;
DeliveryEditViewModel model = db.Deliveries.Include(s => s.Supplier).Include(a => a.Auction).Include(q => q.Quality).Include(t => t.BulbType)
.Where(d => d.DeliveryID == id)
.Select(x => new DeliveryEditViewModel{
DeliveryID = x.DeliveryID,
SelectedCompanyName = x.Supplier.CompanyName
})
.Single();
model.Suppliers = db.Suppliers.Where(s => s.IsActive == true).Select(x => new SelectListItem{
Value = x.SupplierID.ToString(),
Text = x.CompanyName
});
return View(model);
}
問題は、私はすでに私のdatabase.Instead内のデータに基づいてDropDownListForでない設定選択された値を持つことができたということです最初の要素は常にアクティブです。 私はすでにHtml.DropdownListFor selected value not being setからsolutoinを試しましたが、それでも私は実際のものの代わりに最初の値を選択しました。
時間をかけて研究し、すでに大胆な髪の毛が私を止めて助けを求める。 どうすれば可能か考えてください。
ありがとうございました。
'Suppliers'は既に' IEnumerable 'です。ビュー内で' new SelectList(Model.Suppliers、 "Value"、 "Text")を使って別のものを作成しているのはなぜですか? 'SelectedCompanyName'の値をオプションの1つ(つまり' Suppliers'テーブルの 'SupplierID'の値の1つ)と一致するように設定する必要があります(ただし、コードはプロパティが' string'ではなくintでなければならないことを示唆しています) –
@StephenMuecke、ありがとうございました。私はこれを見逃す方法を知らない。今は完璧に動作します。あなたは私を救います) –