I am following this Tutorial on ASP.NET MVC, specifically where it states that providing the String of "MovieType" to the Razor View as follows:@Html.DropDownList("MovieType") will provide the key to DropDownList to find a property in the ViewBag of type IEnumerable<SelectListItem>.
That works just fine.
However, I am unable to get the value that the User selects on my method with [HttpPost] attribute.
Here is my code and what I have tried thus far.
Controller
public class ProductController : Controller
{
private readonly ProductRepository repository = new ProductRepository();
// Get: /Product/Create
public ActionResult Create()
{
var categories = repository.FindAllCategories(false);
var categorySelectListItems = from cat in categories
select new SelectListItem()
{
Text = cat.CategoryName,
Value = cat.Id.ToString()
};
ViewBag.ListItems = categorySelectListItems;
return View();
}
[HttpPost]
public ActionResult Create(Product product)
{
/** The following line is not getting back the selected Category ID **/
var selectedCategoryId = ViewBag.ListItems;
repository.SaveProduct(product);
return RedirectToAction("Index");
}
}
Razor cshtml View
@model Store.Models.Product
<h2>Create a new Product</h2>
@using (@Html.BeginForm())
{
<p>Product Name:</p>
@Html.TextBoxFor(m => m.ProductName)
<p>Price</p>
@Html.TextBoxFor(m => m.Price)
<p>Quantity</p>
@Html.TextBoxFor(m => m.Quantity)
<p>Category</p>
@Html.DropDownList("ListItems")
<p><input type="submit" value="Create New Product"/></p>
}
I tried playing with the overloads for DropDownList, but I am not able to get the value back that the User is selecting.
If anyone sees what I am missing or has any ideas or suggestions, I would be very grateful. Thanks!
Update
Posting Product Model. Note, this was auto-generated by Entity Framework when I created the .edmx.
namespace Store.Models
{
using System;
using System.Collections.Generic;
public partial class Product
{
public long Id { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public System.DateTime DateAdded { get; set; }
public Nullable<long> CategoryId { get; set; }
public virtual Category Category { get; set; }
}
}
Create()method, I put it into theViewBag. I'm trying to figure out if there's a way I can separate the "getting" of the drop-downSelectListItemfrom the property that is sent back on the[HttpPost]. I really don't need theSelectListItemsto come back when the User posts, only the ID of what they selected.