MVC c# List from string in ViewBag

8k views Asked by At

I am retrieving a string from a MS Sql table, it could be just one name or delimited names: For example Tom or Speaker 1, Speaker 2.
I convert the string to list in the controller using:

                    Event cevent = db.Events.Find(id); 
                    string speakers = cevent.Speakers;     
                    ViewBag.speakers = "";
                    if (!String.IsNullOrWhiteSpace(speakers) && 
                    speakers.Contains(","))
                    {
                        ViewBag.speakers = speakers.Split(',').ToList();
                    }
                    else
                    {
                        ViewBag.speakers = speakers;
                    }
                    return View(cevent);

In the view I use the following to display the list:

         <ul>
            @foreach (var item in ViewBag.speakers)
            {
                <li> @item </li>
            }
        </ul>

Works great with the list, I get:

• Speaker 1
• Speaker 2

However, if the ViewBag has just one item, I get:

• T 
• o 
• m 
1

There are 1 answers

5
Wes Doyle On BEST ANSWER

You might consider always passing an enumerable speaker object to the view regardless of whether or not there are one or more than one speaker.

In your view, you are enumerating over the speakers object, which, in the case of the "Tom", is a list of chars. You might try something like this, instead:

In the controller:

ViewBag.speakers = new List<string>();
string speakers = cevent.Speakers;
var listOfSpeakers = speakers.Split(',').ToList();

foreach (var speaker in listOfSpeakers)
{
    ViewBag.speakers.Add(speaker)
}

If you need to format the HTML output differently depending on whether more than one speaker is passed to the view, you can use if(ViewBag.speakers.Count > 1) on the speaker list in a conditional block and handle the output differently in that case.