Mvc控制器从sql查看不可能的问题

时间:2017-01-05 17:36:20

标签: c# sql asp.net-mvc

我正在尝试从SQL中的表中获取所有信息(列,行)并将其作为模型发送到视图。

我也希望它是独特的。

我的控制器:

        MVCEntities me = new MVCEntities();
        List<CarsCategory> arr = me.CarsCategories.ToList();
        return View(arr);

我的观点模型:

@model IEnumerable<CarsCategory>

在视图中,我试图像这样循环某个列:

    <select id="SelectManufacturer">

        @foreach (var i in Model)
        {
            <option value="@i.Manufacturer">@i.Manufacturer</option>
        }
    </select>

如何使其与众不同?当我尝试添加Distinct时,它会给我system.linq.enumerable+<DistinctIterator> ..

2 个答案:

答案 0 :(得分:1)

虽然在视图中处理数据不是一个好方法,但您的解决方案可能如下所示:

<select id="SelectManufacturer">
    @{
        var manufacturers = Model.Select(x => x.Manufacturer).Distinct().ToList();

        foreach (var i in manufacturers)
        {
            <option value="@i">@i</option>
        }
    }
</select>

答案 1 :(得分:1)

控制器应负责向View提供数据,除非您需要不可维护的代码,否则不应使用一堆逻辑来调查视图以尝试聚合此数据。最好的方法是将视图模型扩展为具有多个属性。

模型

public class CategoryModel{
    public List<CarsCategory> CarCategories {get;set;}
    public List<Manufacturer> Manufacturers {get;set;}
}

public class Manufacturer{
    public int Id {get;set;}
    public string Name {get;set;}
}

控制器代码

// you need to ensure that if you are using EF the context is disposed after you are done using it!
using(MVCEntities me = new MVCEntities()) {
  var model = new CategoryModel();
  model.CarCategories = me.CarsCategories.ToList();
  // you need to supply the correct Id and Name locations in your model as you did not share this
  model.Manufacturers = model.CarCategories.Select(x => new Manufacturer(){Id = x.prop.id, Name = x.prop.name}).Distinct();
  return View(model);
}

Razor View

@model CategoryModel

<select id="SelectManufacturer">

    @foreach (var i in Model.Manufacturers)
    {
        <option value="@i.Id">@i.Name</option>
    }
</select>