tags:

views:

54

answers:

3
<p>
    <label for="Tags">Tags:</label>
    <% String tagsText = "";
       foreach (Tag item in Model.Tags)
       {
           tagsText += item.Name + " ";
       }
    %>
    <%= Html.TextBox("Tags", tagsText.Trim()) %>
    <%= Html.ValidationMessage("Tags", "*") %>
</p>

Obviously this code is not perfect, and I admit that. But how would you improve it? It seems a little sloppy to me.

+2  A: 

Not a whole lot cleaner but this has the added benefit of not adding a trailing space at the end of the string.

<p>
    <label for="Tags">Tags:</label>
    <% string tagsText = string.join(" ", (from t in Model.Tags 
                                           select t.Name).ToArray<string>()); %>
    <%= Html.TextBox("Tags", tagsText) %>
    <%= Html.ValidationMessage("Tags", "*") %>
</p>
jessegavin
I forgot to include the Trim() method on my string. Updated
Joe Philllips
This can be written a bit cleaner: `String.Join(" ", Model.Tags.Select(t => t.Name).ToArray<String>())`
roosteronacid
Wow.. even better. Thanks roosteronacid
jessegavin
Good enough for me!
Joe Philllips
+2  A: 

Make a class TagList, add a function:

class TagList
    inherits List<Of Tag>

    function ToJoinedString() as string
        string result = ""
        foreach t as Tag in Me.List
            result = t.Name + " "
        next
        return result.Trim()
    end function

end class

Then on your page:

<p>
    <label for="Tags">Tags:</label>
    <%= Html.TextBox("Tags", Model.Tags.ToJoinedString()) %>
    <%= Html.ValidationMessage("Tags", "*") %>
</p>

This has the advantage of being usable in other places.

egrunin
+1  A: 

Using an extension method like the following:

public static class StringExtensions
{
    public static string Join(this List<string> values, char separator)
    {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < values.Count; i++)
        {
            string value = values[i];
            stringBuilder.Append(value);

            if (i < (values.Count - 1))
            {
                stringBuilder.Append(separator);
            }
        }

        return stringBuilder.ToString();
    }
}

You could make a call like this:

<%@ Import Namespace="YourExtensionsNamespaceHere" %>
<%= Html.TextBox("Tags", tagsText.Join(' ')) %>

You might gain a (very) small performance improvement by using a StringBuilder over some of the other string manipulation options that have been presented.

Adrian Anttila