-1

为什么 foreach 在扩展方法中返回一行?这些代码在普通方法中正常运行。返回一列的原因可能是什么?

public static MvcHtmlString DropDownWithOpt(this HtmlHelper html)
{
    IList<Countries> c = new List<Countries>
    {
        new Countries{ Country = "Georgia", Cities = new List<Cities>
        {
         new Cities{ City="Batumi"},
         new Cities{ City="Tbilisi"},
         new Cities{ City="Zugdidi"}
        }},
        new Countries{ Country = "Turkey", Cities = new List<Cities>
        {
         new Cities{ City="Istanbul"},
         new Cities{ City="Ankara"}
        }}
    };

    var select = new TagBuilder("select");
    var group = new TagBuilder("optgroup");
    var option = new TagBuilder("option");

    foreach (var item in c)
    {

        group.Attributes["label"] = item.Country;
        foreach (var ci in item.Cities)
        {
            option.Attributes["value"] = ci.City.ToString();
            option.SetInnerText(ci.City);
        }
    }
    select.InnerHtml = group.ToString(TagRenderMode.SelfClosing) + option.ToString();
    return MvcHtmlString.Create(select.ToString(TagRenderMode.Normal));
}
4

1 回答 1

0

因为在循环内你正在覆盖它

你可以使用

   Attributes.Add (key, value) 
于 2013-04-30T17:58:13.567 回答