MVC 3 multiple DisplayFor-Templates

后端 未结 4 935
渐次进展
渐次进展 2021-02-07 12:54

I\'m trying to make a custom template for a basket item list. I need a few different templates, as I have different ways of displaying the item, depending on if it\'s on the web

4条回答
  •  被撕碎了的回忆
    2021-02-07 13:26

    I suggest another solution useful even more with lists of heterogeneous objects (i.e. BasketItem subclasses), using the additionalViewData parameter of the DisplayFor method, like:

    @DisplayFor(b=>b.Items, new { layout="row" })
    

    in this way the helper works fine with IEnumerable, calling for each item (subclass of T) the relative DisplayTemplate, passing it the additionalViewData values in the ViewData dictionary.

    The template could so output different code for different layout values.

    In the example above the template named View\Shared\DisplayTemplates\BasketItem (or the name of the subclass) should be like this:

    @model MyProject.BasketItem // or BasketItem subclass
    @{ 
        string layout = ViewData["layout"] as string ?? "default";
    
        switch(layout)
        {
            case "row":
                
    ...
    break; // other layouts ... default: // strongly recommended a default case
提交回复
热议问题