我是MVC dot net的新手。对于电子商务应用程序,我需要填充类别和子类别。通过单击子类别,所有产品都应基于所选子类别显示。但我不知道如何解决这个问题。
这是我的模特
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
public class SubCategory
{
public int SubCategoryId { get; set; }
public string SubCategoryName { get; set; }
public int CategoryId { get; set; }
}
数据库中的子类别表:
SubcategoryId SubCategoryName CategoryId
1 NIKE 1
2 ADIDAS 1
3 FENDI 2
4 GUCCI 2
控制器:
CategoryManager manager=new CategoryManager();
public ActionResult Index()
{
ViewBag.Categories = manager.GetCategories();
ViewBag.SubCategories = manager.GetSubCategories();
return View();
}
查看控制器:
@using EcommerceApp.Models;
@{
List<Category> allCategories = null;
allCategories= ViewBag.Categories;
//...Code for Subcategory....//
}
@if (allCategories!= null)
{
foreach (var catagories in allCategories)
{
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordian" href="#@catagories.CategoryId
">
<span class="badge pull-right"><i class="fa fa-plus"></i></span>
@catagories.CategoryName
</a>
</h4>
</div>
<div id="@catagories.CategoryId" class="panel-collapse collapse">
<div class="panel-body">
<ul>
@*<li><a href="#">....Code For Subcategory...</a></li>*@
</ul>
</div>
</div>
</div>
}
}
SUbCategory的网关:
public List<SubCategory> GetSubCategories()
{
List<SubCategory> subCategoryList = new List<SubCategory>();
SqlConnection connection = new SqlConnection(ConnectionString);
string query = "SELECT * FROM SubCategory";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
SubCategory subCategory = new SubCategory();
subCategory.CategoryId = (int)reader["CategoryId"];
subCategory.SubCategoryName = reader["SubCategoryName"].ToString();
subCategory.SubCategoryId = (int) reader["SubCategoryId"];
subCategoryList.Add(subCategory);
}
return subCategoryList;
}
此代码填充了类别,但我不知道如何填充相应的子类别并根据子类别ID获取产品。在Controller,Model和View中需要写什么或改变什么?