views:

25

answers:

1

I am experimenting with security-trimmed action links in ASP.NET MVC, and am considering using the SecurityTrimmedActionLink helper method described here.

What I would like to do is put a vertical bar between each link like this:

link1 | link2 | link3

But I don't want two vertical bars to appear between links if a link has been trimmed off (the helper method will return an empty string), and there can't be any vertical bars at all if no links or only one link appears. The SecurityTrimmedActionLink helper method cannot assist with the vertical bars; it will have no knowledge of the other links.

Can this be achieved with some simple logic in the view?

A: 

After giving it some thought, I created a new HtmlHelper method:

using System.Text;

namespace System.Web.Mvc.Html
{
    public static class HtmlHelpers
    {
        public static string Delimit(
             this HtmlHelper h, string delimiter, params string[] s)
        {
            bool flag = false;
            StringBuilder b = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
                if (s[i].Length > 0)
                    if (flag)
                        b.Append(delimiter + s[i]);
                    else
                    {
                        flag = true;
                        b.Append(s[i]);
                    }
            return b.ToString();
        }
    }
}

Which should allow me to write:

<% =Html.Delimit("|", 
        Html.SecurityTrimmedActionLink(...),
        Html.SecurityTrimmedActionLink(...),
        ...
    ); 
$>
Robert Harvey