开发者

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜