MVC 3 multiple DisplayFor-Templates

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

    I liked Dan's answer but just adjusted slightly as it can work for any IEnumerable:

    using System.Collections;
    using System.Text;
    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    
    namespace YourProject.Whatever
    {
        public static class DisplayExtensions
        {
            public static MvcHtmlString DisplayForIEnumerable(this HtmlHelper html, IEnumerable model, string templateName)
            {
                var tempResult = new StringBuilder();
    
                foreach (var item in model)
                {
                    var item1 = item;
                    tempResult.Append(html.DisplayFor(m => item1, templateName));
                }
    
                return MvcHtmlString.Create(tempResult.ToString());
            }
        }
    }
    

    And of course:

    @Html.DisplayForIEnumerable(Model.Organizations, "NameOfYourDisplayTemplate")
    

提交回复
热议问题