現在、ViewBag を使用してビューからデータを取得し、モデルを更新しています。選択したアイテムを取得するドロップダウンリストを使用しており、コントローラーで選択した「顧客モデル」を更新しています。これは良い方法ではないことはわかっています...フォームコレクションパラメーターを使用せずに、ドロップダウンリストの選択で「顧客モデル」を更新する方法を教えてください。
コントローラ
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Customer customer, FormCollection form)
{
if (ModelState.IsValid)
{
// Get selectected title from dropdownlist
customer.Title = form["TitleDropDownList"];
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
意見
<tr>
<td>
@Html.LabelFor(model => model.Title)
</td>
<td>
@Html.DropDownList("TitleDropDownList")
@Html.ValidationMessageFor(model => model.Title)
</td>
</tr>
私のGetメソッドは...
public ActionResult Create()
{
// Create title dropdownlist list for new customers
List<SelectListItem> titleDropDownList = new List<SelectListItem>();
titleDropDownList.Add(new SelectListItem { Text = "Mr", Value = "Mr" });
titleDropDownList.Add(new SelectListItem { Text = "Mrs", Value = "Mrs" });
titleDropDownList.Add(new SelectListItem { Text = "Miss", Value = "Miss" });
titleDropDownList.Add(new SelectListItem { Text = "Ms", Value = "Ms" });
ViewBag.TitleDropDownList = titleDropDownList;
return View();
}