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.

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

I forgot to include the Trim() method on my string. Updated
This can be written a bit cleaner: String.Join(" ", Model.Tags.Select(t => t.Name).ToArray<String>())
2

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.

Comments

1

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.

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.