Use properties of different models in view (.net M

2019-06-13 19:47发布

问题:

I am learning MVC and display a list of products in a view.

@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>

The products belong to categories, which are displayed in the right column. I now want to filter the products by categories, for which I would like to use a dropdownlist control. I found @Html.DropDownListFor(), but as far as I understand, this will only give me properties of the currently underlying model (Product).

My controller:

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

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

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

回答1:

You could do something like this. Just create a class with the info that you need.

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; }

}

Then your controller:

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);
    }
}

Finally, your view

@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>