代码之家  ›  专栏  ›  技术社区  ›  Joe Phillips

用转换为字符串的数据列表填充html.textbox

  •  3
  • Joe Phillips  · 技术社区  · 15 年前
    <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>
    

    显然,这段代码并不完美,我承认。但是你会怎么改进呢?我觉得有点马虎。

    3 回复  |  直到 15 年前
        1
  •  2
  •   jessegavin    15 年前

    不是很干净,但这样做的好处是不会在字符串末尾添加尾随空格。

    <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
  •  2
  •   egrunin    15 年前

    创建类标记列表,添加函数:

    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
    

    然后在您的页面上:

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

    这有在其他地方可用的优势。

        3
  •  1
  •   Adrian Anttila    15 年前

    使用如下扩展方法:

    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,您可能会获得(非常)小的性能改进,而不必使用其他已提供的一些字符串操作选项。