简体   繁体   中英

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.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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