简体   繁体   中英

'object' does not contain a definition error in Asp.Net MVC

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?

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);

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