Why foreach returns one row inside extension method?

79 views Asked by At

Why foreach returns one row inside extension method?These codes run properly inside normal method.What could be reason for return one column?

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

There are 1 answers

0
Dan Hunex On

Because inside the loop you are overwriting it

you may use

   Attributes.Add (key, value)