Reputation: 6348
I am new in ASP.NET MVC.
I have a problem like below.
In Controller i have a code like this.
var students= db.Sagirdler.Where(x => x.SinifID == sinif.SinifID).
Select(m => new {m.Name, m.Surname}).ToList();
TempData["Students"] = students;
return RedirectToAction("Index", "MyPage");
This is my Index Action in MyPageController where I redirect and i call View.
public ActionResult Index()
{
ViewBag.Students = TempData["Students"];
return View();
}
And in View I use this code.
@{
ViewBag.Title = "Index";
var students = ViewBag.Students;
}
@foreach (var std in students)
{
@std.Name
<br/>
}
It says:
'object' does not contain a definition for 'Name'
What is the problem? How can I solve it?
Upvotes: 0
Views: 1081
Reputation: 28157
You want to use
ViewBag.Students = students;
instead of TempData
.
What I think you're trying to achieve would be better implemented like so:
Create a class
public class StudentViewModel
{
public string Name { get;set;}
public string Surname {get;set;}
}
then in your view using
@model IEnumerable<StudentViewModel>
@foreach (var student in Model)
{
...
}
And in your controller
var students = db.Sagirdler.Where(x => x.SinifID == sinif.SinifID)
.Select(m => new StudentViewModel { Name = m.Name, Surname = m.Surname} )
.ToList();
return View(students);
Upvotes: 2