I recently got into Asp.Net MVC development (using MVC 6 and Asp 5).
I am trying to create a relationship between 2 model classes. A Product and a Category. The Product belongs to a category, and thus a category can contain many products.
This is my model code:
public class Category
{
public int id { get; set; }
public string name { get; set; }
public virtual ICollection<Product> product { get; set; }
}
public class Product
{
public int id { get; set; }
public string name { get; set; }
public decimal price { get; set; }
public virtual Category category { get; set; }
}
Then i created 2 controllers from the models using entity framework with views and then i perform the migration. I then have CRUD operations for both which works fine, but the problem is that i cant assign a product to a category. I can only set the name and price of a product using the generated views.
Hope someone can help. Obviously i'm expecting some sort of a drop-down that shows all categories when creating a product, so i can link them together.
Thanks.
* EDIT * ProductsController - create method:
// POST: Products/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
_context.Product.Add(product);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
Again, please note that i am not trying to add the functionality manually. I am trying to get the whole scaffolding / migration procedure to work with object relationships, so it can generate it for me automatically and speed up my development process.
* EDIT 2 * The Product model was changed to:
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public decimal ProductPrice { get; set; }
[ForeignKey("Category")]
public int CategoryID { get; set; }
public virtual Category category { get; set; }
}
This will now create a dropdown list of categories when i'm creating a product. HOWEVER - the list is empty even if i create a category, so something is still missing? Maybe the category model needs additional information? This is how it displays the list in the GET create:
// GET: Products/Create
public IActionResult Create()
{
ViewData["CategoryID"] = new SelectList(_context.Category, "id", "category");
return View();
}
Which is just an empty list... Almost there, but not quite yet.