开发者

DisplayTemplate code need fix/feedback

开发者 https://www.devze.com 2023-03-09 02:36 出处:网络
I have a DisplayTemplate called _FooterMenu in which below dynamic footer menu is coded. Few things to ask

I have a DisplayTemplate called _FooterMenu in which below dynamic footer menu is coded.

Few things to ask

Is there any way to simplify DisplayTemplate code?

Should I used HtmlHelper to hide logic?

Code in layout page

@Html.DisplayForModel("_FooterMenu")

//DisplayTemplate code.

@model HomeViewModel

@{var distMenu = Model.FooterMenu.Where(c => c.Title != null).Select(m => new {Title = m.Title}).Distinct() ;}
@foreach (var i in distMenu)
{
    <div class="linksarea">
    <h5>@i.Title</h5>
        <ul>
                @foreach (var item in Model.FooterMenu.FindAll(x => x.Title == i.Title))开发者_开发技巧
                {
                    <li>
                        @Html.ActionLink(@item.DisplayName, "Page", "Home", new { name = @item.UrlName }, null)
                    </li>   
                }                                                   
        </ul>
    </div>
}   


I think the key to optimizing your code is to use a "GroupBy" for your Footer Menu Items, this will alleviate the need for 2 ForEach loops. I mocked up your MVC app, here is the code snippet I came up with:

   @{
        var distMenu = Model.FooterMenu.GroupBy(q => q.Title);
    }

    @foreach (var grp in distMenu)
    { 
        <div class="linksArea">
            <h5>@grp.Key</h5>
            <ul>
            @foreach(var item in grp)
            {
                <li>
                    @Html.ActionLink(@item.DisplayName, "Page", "Home", new { name = @item.Url }, null)
                </li>   
            }
            </ul>
        </div>
    }

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消