views:

175

answers:

2

Hello,

I have menu on my website, some links are internal and builds with Html.ActionLink method, and some are external and builds with tag.

But I don't like this code, I prefere to have one line instead of two lines. But I don't know how to do it, can anybody help me please?

<table width="100%" border="0" cellpadding="0" cellspacing="0">
<%
    foreach (AtomicCms.Core.DomainObjectsImp.MenuItem item in Model.MenuItems)
    {
        if (!item.IsExternalUrl)
        {
%>
<tr align="left">
    <td>
        <%=Html.ActionLink(Html.Encode(item.Title), "Content", "Home", new { id = item.Entry.Id, name = item.Entry.Alias }, new {title = Html.Encode(item.Title), @class="mainlevel"})%>
    </td>
</tr>
<%}
        else
        {
%>
<tr align="left">
    <td>
        <a href="<%=item.NavigateUrl %>" class="mainlevel">
            <%=Html.Encode(item.Title)%></a>
    </td>
</tr>
<%} %>
<%
    } %>

+3  A: 

I would extract this out to an html helper method. It would look something like:

public static string MenuItemLink(this HtmlHelper html, MenuItem item) {
    ...
}

Your view code would look somthing like: <%= Html.MenuItemLink(item) %>

jrotello
I found solution to build extension method for UrlHelper instead of HtmlHelper and it works for me. Thanks a lot.<a href="<%=Url.BuildMenuLink(item) %>" class="mainlevel"> <%=Html.Encode(item.Title)%></a>
Alexander Shapovalov
A: 

Why not build the link in your controller and incorporate it into the model? Then you only need the second line? That is, your MenuItem model is a collection of links and their associated text. Use the UrlHelper in the Controller to create the link in the controller.

tvanfosson