Joe Phillips
Joe Phillips

Reputation: 51200

Populate an Html.TextBox with a List of data that is converted to a String

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

Upvotes: 3

Views: 546

Answers (3)

Adrian Anttila
Adrian Anttila

Reputation: 2038

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.

Upvotes: 1

egrunin
egrunin

Reputation: 25083

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.

Upvotes: 2

jessegavin
jessegavin

Reputation: 75690

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>

Upvotes: 2

Related Questions