简体   繁体   English

在视图中显示实体框架查询的结果

[英]Display result of an Entity Framework query in a view

I'm new to Entity Framework, I want to display the result of a query which was performed in a controller on my view page. 我是Entity Framework的新手,我想在我的视图页面上显示在控制器中执行的查询结果。

Here is my code in the controller I don't know where to go from here please help I appreciate any help from any one thanks: 这是我在控制器中的代码,我不知道从这里去哪里,请帮助我感谢任何人的任何帮助,谢谢:

public ActionResult StartQiz()
{          
    using (var question = new Quizdb()) 
    {    
          var quest = (from q in question.Exams
                       where q.ExamType.StartsWith("C#")
                       select q);

          ViewBag.querry = quest;
    }

    return View();
} 

You don't need to pass the query result to ViewBag.just return the result to the view.(right click on View(quest) then choose add view ;in case that you don't have corresponding ViewModel class) 您不需要将查询结果传递给ViewBag。只需将结果返回到视图即可。(右键单击View(quest)然后选择add view;如果您没有相应的ViewModel类)

public ActionResult StartQiz()
{         
    using (var question = new Quizdb()) 
    {    
          var quest = (from q in question.Exams
                       where q.ExamType.StartsWith("C#")
                       select q).ToList();
          return View(quest);
    }  
} 

You are currently using the ViewBag object to pass your data from action method to the view. 您当前正在使用ViewBag对象将数据从操作方法传递到视图。 This can be done, but you might want consider using the model approach. 可以做到这一点,但是您可能要考虑使用模型方法。

public ActionResult StartQiz()
{          
    using (var question = new Quizdb()) 
    {    
      var quest = (from q in question.Exams
                       where q.ExamType.StartsWith("C#")
                       select q);


      return View(quest);
    }
} `

In your view the first line should declare the model: 您认为第一行应声明模型:

 @model IEnumerable<Type>

Then you can access your data like this: 然后,您可以像这样访问数据:

@foreach(var exam in Model) 
{
   <p>exam.Title</p>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM