在视图MVC中显示控制器的列表

时间:2017-06-23 05:05:41

标签: c# asp.net asp.net-mvc razor

enter image description here我有一个控制器,它使用Entity framwework从用户定义的函数中获取数据。我试图在视图中显示我的数据并填充我的表。

我的控制器看起来像这样:

public ActionResult Index()
    {
        var description = "Toyota";
        QuotingEngineEntities1 vehicles = new QuotingEngineEntities1();


        List<object> list = new List<object>();

        using (var context = new QuotingEngineEntities1())
        {

            var vehicle = from s in context.fn_GetVehicle(description)
                           select new
                           {
                               s.MAKE,
                               s.MODEL,
                               s.PRICE,
                               s.POWER,
                               s.Transmission
                           };


            list.Add(vehicle.FirstOrDefault());


        }

        ViewBag.list = list;

        return View(ViewBag.list);
    }

AND MY View看起来像这样

@foreach (var v in ViewBag.list)
    {
       <li>@v.MODEL</li> //i get an error 
       <br />
    }

我终于搞定了。在将数据添加到列表之前,我必须遍历数据。

public ActionResult Index()
        {
            var description = "Toyota";

            List<fn_GetVehicle_Result> list = new List<fn_GetVehicle_Result>();

                using (var context = new QuotingEngineEntities1())
                {

                   var query = context.fn_GetVehicle(description);

                    foreach (var v in query)
                    {

                      list.Add(v);

                    }

                     ViewBag.list = list;
                }



            return View("Index",ViewBag.list);
        }



enter code here

1 个答案:

答案 0 :(得分:0)

您正在尝试将Viewbag与列表数据一起使用,但不建议这样做,您不必将Viewbag添加到View()方法中。它由控制器自动发送到视图中。

我建议使用ViewModel或ExpandoObject将您的集合发送到视图中。你可以实现如下

<强> //控制器

public ActionResult Index()
{

        using (var context = new QuotingEngineEntities1())
        {

            var vehicle = from s in context.fn_GetVehicle(description)
                           select new
                           {
                               s.MAKE,
                               s.MODEL,
                               s.PRICE,
                               s.POWER,
                               s.Transmission
                           };

            dynamic yourmodel = new ExpandoObject(); 
            yourmodel.Vehicles = vehicle.ToList();

        }


        return View(yourmodel);
}

//查看

@using YourProject; // Your Project Name 
@model dynamic

@foreach (var v in model.Vehicles)
{
    <li>@v.MODEL</li> 
    <br />
}