我正在使用MS northwind数据库,并使用Entity Framework。 我想创建新产品,并使用dropdownList从Category Table加载CategoryName。
public ActionResult Create()
{
var categories = from c in _en.Categories select c;
ViewData["CategoryID"] = new SelectList(categories, "CategoryID", "CategoryName");
return View();
}
<p>
<label for="ds">CategoryID:</label>
<%=Html.DropDownList("CategoryID", (SelectList)ViewData["CategoryID"])%>
</p>
问题:如何从dropdownList保存数据?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "ProductID")] Products productToCreate)
{
if (!ModelState.IsValid)
return View();
var c = _en.Categories.FirstOrDefault(z => z.CategoryID == ??? XXXX ???);
productToCreate.Categories = c;
_en.AddToProducts(productToCreate);
_en.SaveChanges();
return RedirectToAction("Index");
}
如何从dropdownList获取CategoryID?
答案 0 :(得分:1)
只需将CategoryID添加到参数中即可。
public ActionResult Create([Bind(Exclude = "ProductID")] Products productToCreate, string CategoryID)