2012-01-04 44 views
0

我正在学习MVC并在视图中显示产品列表。在视图中使用不同模型的属性(.net MVC)

@model IEnumerable<Domain.Model.Product> 

<table> 
    <tr> 
     <th style="width:50px; text-align:left">Id</th> 
     <th style="text-align:left">Name</th> 
     <th style="text-align:left">Category</th> 
    </tr> 

@foreach (var item in Model) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.Id) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.Name) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.Category.Name) 
     </td>    
    </tr> 
} 

</table> 

产品属于类别,显示在右栏。我现在想要按类别过滤产品,为此我想使用下拉列表控件。我发现@ Html.DropDownListFor(),但据我所知,这只会给我目前基础模型(产品)的属性。

我的控制器:

public class ProductController : Controller 
{ 
    ProductRepository pr = new ProductRepository(); 

    public ActionResult Default() 
    { 
     List<Product> products = pr.GetAll(); 

     return View("List", products); 
    } 
} 
+1

哎,你需要传递的不仅仅是产品更多。可能是类别和产品的某种连接,或者是新的“模型”类别和产品类别和产品以及一些适合的“查找”方法。 – 2012-01-04 16:20:46

回答

0

你可以做这样的事情。只需创建一个包含所需信息的课程。

public class ProductsModel 
{ 
    public ProductsModel() { 
      products = new List<Product>(); 
      categories = new List<SelectListItem>(); 
    } 

    public List<Product> products { get;set; } 
    public List<SelectListItem> categories { get;set; } 

    public int CategoryID { get;set; } 

} 

然后控制器:

public class ProductController : Controller 
{ 
    ProductRepository pr = new ProductRepository(); 

    public ActionResult Default() 
    { 
     ProductsModel model = new ProductsModel(); 
     model.products = pr.getAll(); 

     List<Category> categories = pr.getCategories(); 
     model.categories = (from c in categories select new SelectListItem { 
      Text = c.Name, 
      Value = c.CategoryID 
     }).ToList(); 

     return View("List", model); 
    } 
} 

最后,你的看法

@model IEnumerable<Domain.Model.ProductsModel> 

@Html.DropDownListFor(m => model.CategoryID, model.categories) 

<table> 
    <tr> 
     <th style="width:50px; text-align:left">Id</th> 
     <th style="text-align:left">Name</th> 
     <th style="text-align:left">Category</th> 
    </tr> 

@foreach (var item in Model.products) { 
    <tr> 
     <td> 
      @item.Id 
     </td> 
     <td> 
      @item.Name 
     </td> 
     <td> 
      @item.Category.Name 
     </td>    
    </tr> 
} 

</table> 
+0

谢谢!但@model只能是Domain.Model.ProductsModel。你需要什么CategoryID?你什么时候设置它? – AGuyCalledGerald 2012-01-05 11:11:28

+0

当您从下拉列表中选择一个项目时,它将该值存储到模型的CategoryID中。通过这种方式,当您回发到服务器通过ajax或常规进行过滤时,网站会知道您要过滤哪个类别。 – uadrive 2012-01-05 16:39:42

相关问题