Search code examples
c#.net-corenancy

Iterating through List with Super Simple View Engine without a model


I'm trying to create a simple example of how to use NancyFx's Super Simple View Engine to iterate over a list of strings sent to the front-end with ViewBag while running on .Net Core. But when I attach my List to the @Each statement, it simply gives an error. However, I was able to print the List after I wrapped it in a custom object.

public class ViewHolder
{
    public List<string> listOfThings { get; set; }
}
...
ViewHolder boxIt = new ViewHolder();
boxIt.listOfThings = someList;
ViewBag.viewPasser = boxIt;

And then on the front end:

@Each.Context.ViewBag.viewPasser.listOfThings
    @Current
@EndEach

This achieves what I want, but I don't understand why the @Each won't recognize my List without the wrapper class. Is there a way to do this without the extra boxing?


Solution

  • You could accomplish what you are looking for by passing your collection in as a Model to the view instead of using the viewbag. Here is an example of how to do that:

        in module
        ...
        var items = new List();
        items.Add( "Item1" );
        items.Add( "Item2" );
        items.Add( "Item3" );
        return View["Index", items];
    
    
        in view
        ...
        @Each
            @Current
        @EndEach
    

    I dug into the NancyFx source code and stepped through the file that was ultimately responsible for the issue you are seeing. What is happening is that in that code Nancy is trying to cast the collection in the ViewBag to an IEnumerable and is failing. It appears that when you place the collection directly into the ViewBag and Nancy tries to do the cast the type of that collection is no longer List but just dynamic so the cast fails with a null and Nancy returns [ERR!]. However if you drop that list in a class and place an instance of that class in the ViewBag it is able to reconcile the type correctly and perform the cast. Still not super useful but hopefully a little more insight into why the apparent discrepancy.