How can I use Html.DisplayFor inside of an iterator?

前端 未结 6 1476
死守一世寂寞
死守一世寂寞 2020-12-03 06:23

I am loving MVC 2. The whole thing just fits the web so well.

There is one piece of functionality, however, that I am unable to coax out of the Html.

6条回答
  •  不思量自难忘°
    2020-12-03 07:05

    Html.DisplayFor can automatically iterate over collections, displaying a partial view for each element in the collection.

    The first thing you need to do is create an actual model class, with the collection being a property of the class.

    public class Bar
    {
        public IEnumerable foo { get; set; }
    }
    

    Return this class from your controller instead of the raw collection.

    Secondly you need a display template for the Foo class. Display templates are partial views that need to be placed in the folder Views/Shared/DisplayTemplates.

    Edit: You can have them in your controller subfolder of Views as well if you want to limit the template to a particular controller. See this question for more information.

    Here is an example in razor syntax:

    @model YourNameSpace.Foo
    

    @Model.BarBaz

    Save it as Foo.cshtml in the DisplayTemplates folder given above.

    This template is pretty simple because it is based on your example where you are only displaying a string, but if the collection elements where a class with its own properties you could create a more elaborate template.

    Now in the original view, you can get rid of the loop entirely and just write

    @Html.DisplayFor(m => m.foo)
    

    Notice foo is the name of the property in your new model class that contains the old collection you looped over before.

    DisplayFor will automatically know that the foo property is of type (collection of) Foo and pick up the Foo.cshtml template in the DisplayTemplates folder and show it once for each element in foo.

提交回复
热议问题