2

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>
<%} %>
<%
    } %>

2 Answers 2

3

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) %>

Sign up to request clarification or add additional context in comments.

1 Comment

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>
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.