MVC 3 multiple DisplayFor-Templates

后端 未结 4 987
渐次进展
渐次进展 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:30

    That's a good idea, Darin. I'm lazy though, so I'd like to take it one step further and make an actual helper that wraps this. I also took out the lambda expression to simplify it for my case, but you can easily add that functionality back in.

        public static class DisplayTextListExtension
    {
        public static MvcHtmlString DisplayForList(this HtmlHelper html, IEnumerable model, string templateName)
        {
            var tempResult = new StringBuilder();
    
            foreach (var item in model)
            {
                tempResult.Append(html.DisplayFor(m => item, templateName));
            }
    
            return MvcHtmlString.Create(tempResult.ToString());
        }
    }
    

    Then the actual usage looks like:

                                    @Html.DisplayForList(Model.Organizations, "infoBtn")
    

提交回复
热议问题