Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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);
}*@

Posted
Comments
Karthick Viswanathan 23-Jun-14 6:28am    
Hi,
You mean cascading dorpdown? if so you can use ajax to fill products after select a category

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900