Html 在mvc中填充下拉列表的更好方法

Html 在mvc中填充下拉列表的更好方法,html,asp.net-mvc,drop-down-menu,html-select,Html,Asp.net Mvc,Drop Down Menu,Html Select,我尝试创建带有标签的下拉列表 <select name="manufacturer" class="form-control"> <option>@null</option> @foreach (var item in Model) { <option>@item.Manufacturer</option> }

我尝试创建带有标签的下拉列表

        <select name="manufacturer" class="form-control">
            <option>@null</option>
            @foreach (var item in Model) {
                <option>@item.Manufacturer</option>
            }
        </select><br>

那么有什么方法可以解决这个问题呢?

既然你知道为什么会发生这种情况

这是因为它使用从控制器传递的模型,该模型并不总是包含数据库中的所有项。由于分页或搜索后

那为什么不把它修好呢。如果您还没有验证表,可能需要为制造商提供一个单独的验证表

型号:

public class ProductsModel
{
    public IPagedList<Products> CurrentProducts {get; set;}
    public int ManufacturerId {get; set;}
    public int MinPrice{get; set;}
    public int MaxPrice{get; set;}
}
在视图中,创建如下下拉列表:

@model MyNameSpace.ProductsModel
@Html.DropDownListFor(model=> model.ManufacturerId, string.Empty);

谢谢你的回复。在我发布问题之前,我考虑了您的建议,但是有没有办法不为制造商创建单独的表,因为我没有。您可以在执行分页逻辑之前保存ViewBag.Manufacturer_Id。这几乎有帮助。我尝试了这种方法ViewBag.Manufacturers=从p in_repository.Product选择p.Manufacturer;在视图中,将其插入到foreach循环中。但是Get RuntimeBinderExceptionsaying“string”不包含“Manufacturer”建议的定义?能否将for循环粘贴到此处?当然。这里是ViewBag.Manufacturers{@item.Manufacturer}
[HttpGet]
public ViewResult CurrentProducts()
{
    ProductsModel model = new ProductsModel();
    model.CurrentProducts = _repository.Product;
    ViewBag.ManufacturerId = from p in _repository.Product select p.Manufacturer;
    return View(model);
}

[HttpPost]
public ViewResult CurrentProducts(ProductsModel model)
{
    if(ModelState.IsValid)
    {
        model.CurrentProducts = _repository.Product.Where(t=>t.ManufacturerId == model.ManufacturerId);
        ViewBag.ManufacturerId = from p in _repository.Product select p.Manufacturer;
    }
    return View(model);
}
@model MyNameSpace.ProductsModel
@Html.DropDownListFor(model=> model.ManufacturerId, string.Empty);