Post action Create in asp.net MVC
i'm using MS northwind database, and use Entity Framework. I want to create new product, and use dropdownList to load CategoryName from Category Table.
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>
Question: How to Save data from 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");
}
how to get CategoryID from dropdownList?
Just add CategoryID to the arguments.
public ActionResult Create([Bind(Exclude = "ProductID")] Products productToCreate, string CategoryID)
精彩评论