Tags: <% String tagsText = ""; foreach ...">

Fill in 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 it. But how would you improve it? It seems a little careless to me.

+3
source share
3 answers

Not much cleaner, but this has the added benefit of not adding end space at the end of the line.

<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>
+2
source

Create a TagList class, 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 that it can be used in other places.

+2
source

, :

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();
    }
}

:

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

() , StringBuilder , .

+1

Source: https://habr.com/ru/post/1730966/


All Articles