Jon Gallant

How to create an MVC Razor view for a generic List property

2 min read

You have a model that has a property of type List. You write a view and your first inclination is to create a cshtml file called List.cshtml, but that doesn’t work. There’s a trick and it has to do with the way List<Tis expressed as a type in reflection form.

You can see this by calling GetType().Name on a List

List<string> strings = new List<string>();
Console.WriteLine(strings.GetType().Name);
```javascript
![Screenshot](/images/blog/f4404b5bad30_DE9C/image.png)
As you can see, the reflected name is List\`1, NOT List.
MVC (by default) will try to map the property to List\`1.cshmlt, not List.cshtml.
So you have two options.
## 1. Name your DisplayTemplate List\`1.cshtml and let MVC automatically resolve the property template
@Html.DisplayFor(m => ss.Items);
![Screenshot](/images/blog/f4404b5bad30_DE9C/image_3.png)
## 2. Specify a Template Name when calling DisplayFor
```csharp
@Html.DisplayFor(m => ss.Items, "Items");

Screenshot

When you reference the @model in the view use either IList or List or if you know the type at design time then just use that i.e. List

My preference is to use option #2 because you’ll likely have many other classes that use List<Tand you’ll likely want to specify a different display template for each of them.

Jon

Please enable JavaScript to view the comments powered by Disqus.

Share:
Share on X