0

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?

2
  • 6
    TempData and ViewBag are not the same thing. Commented Mar 8, 2014 at 12:00
  • why are you not returning a model back to the view? why store it in TempData or ViewBag? Both are bad practices and you are defeating the purpose of MVC (M being the Model which gets passed to the V (View) to render on the page). I do see you are doing a RedirectToAction but are you redirecting to the same action? why? if different then are you sure you should be doing it where your code currently is? Commented Mar 8, 2014 at 12:11

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.