I want to create a razor view with one dropdown list which shows category names and list of products based on the category name selected in category drop.
Model class: -
public class InventoryContext : DbContext
{
public InventoryContext()
: base("DefaultConnection")
{} DbSet<categorymodel> Category { get; set; }
public DbSet<productmodel> Product { get; set; }
}
[Table("Category")]
public class CategoryModel
{
[Key]
public int CategoryId
{
get;
set;
}
[StringLength(50)]
[Required(AllowEmptyStrings = false)]
public string CategoryName
{
get;
set;
}
public string CategoryDesc
{
get;
set;
}
public DateTime AddedOn
{
get;
set;
}
[Required(AllowEmptyStrings = false, ErrorMessage = "Select status")]
public int Status
{
get;
set;
}
}
[Table("Product")]
public class ProductModel
{
//int categoryId;
[Key]
public int ProductId
{
get;
set;
}
[StringLength(50)]
[Required(AllowEmptyStrings = false)]
public string ProductName
{
get;
set;
}
public string ProductDesc
{
get;
set;
}
public DateTime AddedOn
{
get;
set;
}
[Required(AllowEmptyStrings = false, ErrorMessage = "Select status")]
public int Status
{
get;
set;
}
//[ForeignKey("Product_CategoryId")]
public int CategoryId
{
get;
set;
}
}
public class InventoryModels
{
public List<categorymodel> IM_CategoryModel { get; set; }
public List<productmodel> IM_ProductModel { get; set; }
public InventoryModels(List<categorymodel> _categoryModel, List<productmodel> _productModel)
{
IM_CategoryModel = _categoryModel;
IM_ProductModel = _productModel;
}
}
Controller Action of ProductController.cs: -
public ActionResult Index(int id = 0)
{
var productList = db.Product.Where(q => q.CategoryId == id || id == 0).ToList();
List<categorymodel> categoryList = db.Category.ToList(); // new SelectList(db.Category, "CategoryId", "CategoryName", db.Category);
InventoryModels objInventoryModels = new InventoryModels(categoryList, productList);
return View(objInventoryModels);
}
Razor View:-
@model MvcAppTest.Models.InventoryModels
Please help me to complete below dropdownlist for category.
Note: I am not posting product list of code of view coz it is simple and working fine.
Only help me to create dropdown list from my viewmodel
@*@{
@Html.DropDownList("IM_CategoryModel[0].CategoryId", Model.IM_CategoryModel);
}*@