为什么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));
}
答案 0 :(得分:0)
因为你在循环中覆盖它
你可以使用
Attributes.Add (key, value)