user793468
user793468

Reputation: 4976

converting String to List

I have a controller which pulls a list of students and displays in a view, Below part of my controller action which stores students in a list and then to a TempData Variable. Then I redirect it to a different action to display the list in a view:

var StudentsList = (from s in data.vwStudents.Where(a => a.StudentID == Id)
                   group s by s.StudentName into g
                   select g.Key).ToList();

TempData["StudentsList"] = StudentsList;

return RedirectToAction("DisplayStudents");

I pass the TempData["StudentList"] variable to another Controller Action:

    [HttpGet]
    public ActionResult DisplayStudents()
    {
        ViewData["StudentsList"] = TempData["StudentsList"];
        return View();
    }

Here is how I display students in a view:

         <%= ViewData["StudentsList"]%> <br /><br />

The issue is, I am not able to see students, Instead I see:

System.Collections.Generic.List`1[System.String] 

Do I need to convert the TempData to a list before passing it to the view? or do I do it in the view? Also, How do I convert TempData variable to a list?

Thanks in advance

Upvotes: 1

Views: 1213

Answers (2)

Justin Morgan
Justin Morgan

Reputation: 30700

What you have is a list of names, not a single name; if your model were just a string, the engine could dump it onto the page as-is and call it good. But it doesn't know what to do with a list, because there's any number of ways to arrange something like that.

It doesn't know what you want: a comma-separated list? A bunch of bullet points? A table? The engine has no idea, so it gives up and asks you for instructions.

So you need to tell the view how to display your list. How you do that is up to you, but I'll give you an example. I'm more familiar with the Razor engine, so I'll attempt this in that syntax:

<ul>    
    @foreach (string name in (List<string>)ViewData["StudentsList"])
    {        
        <li>@name</li>        
    }    
</ul>

That should generate a bulleted list of student names. If you want it in a different format, just use divs or something instead of the ul/li construct.

Upvotes: 2

Beenish Khan
Beenish Khan

Reputation: 1583

Use following :

string.Join(",",(List<string>)ViewData["StudentsList"])).ToArray());

Upvotes: 4

Related Questions