如何在c#中编写HTML select标签

时间:2017-11-24 11:12:45

标签: c# html select webforms

我想在我的C#项目中编写HTML。我想在我的项目中插入一些:

<select>
    <optgroup label="Swedish Cars">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
    </optgroup>
    <optgroup label="German Cars">
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </optgroup>
</select>

我希望看起来像这样:

string a = Commissie.First();
<select>
    <optgroup label = a>
    for (int i=0; i<Commissie.Count; i++)
    {
        if(a == Commissie[i])
        {
            <option value = Titel[i]> Titel[i] </option>
        }
        else
        {
            </optgroup>
            a = Commissie[i];
            <optgroup label = a>
            < option value = Titel[i] > Titel[i] </option>
        }
    }
    </optgroup>
</select>

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

我使用THIS中实现的示例详细阐述了我的答案  答案。

默认DropDownList未涵盖SELECT元素中OPTGROUP的需求。您需要实现DropDownList类的扩展。

扩展类项目(DLL)

- 创建一个图书馆类项目
- 添加System.Web DLL
- 添加扩展类(下面的示例)

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyProjectName
{
    public class ExtendedDropDownList : DropDownList
    {
        public const string OptionGroupTag = "optgroup";
        private const string OptionTag = "option";
        protected override void RenderContents(HtmlTextWriter writer)
        {
            ListItemCollection items = this.Items;
            int count = items.Count;
            string tag;
            string optgroupLabel;
            if (count > 0)
            {
                bool flag = false;
                string prevOptGroup = null;
                for (int i = 0; i < count; i++)
                {
                    tag = OptionTag;
                    optgroupLabel = null;
                    ListItem item = items[i];
                    if (item.Enabled)
                    {
                        if (item.Attributes != null && item.Attributes.Count > 0 && item.Attributes[OptionGroupTag] != null)
                        {
                            optgroupLabel = item.Attributes[OptionGroupTag];

                            if (prevOptGroup != optgroupLabel)
                            {
                                if (prevOptGroup != null)
                                {
                                    writer.WriteEndTag(OptionGroupTag);
                                }
                                writer.WriteBeginTag(OptionGroupTag);
                                if (!string.IsNullOrEmpty(optgroupLabel))
                                {
                                    writer.WriteAttribute("label", optgroupLabel);
                                }
                                writer.Write('>');
                            }
                            item.Attributes.Remove(OptionGroupTag);
                            prevOptGroup = optgroupLabel;
                        }
                        else
                        {
                            if (prevOptGroup != null)
                            {
                                writer.WriteEndTag(OptionGroupTag);
                            }
                            prevOptGroup = null;
                        }

                        writer.WriteBeginTag(tag);
                        if (item.Selected)
                        {
                            if (flag)
                            {
                                this.VerifyMultiSelect();
                            }
                            flag = true;
                            writer.WriteAttribute("selected", "selected");
                        }
                        writer.WriteAttribute("value", item.Value, true);
                        if (item.Attributes != null && item.Attributes.Count > 0)
                        {
                            item.Attributes.Render(writer);
                        }
                        if (optgroupLabel != null)
                        {
                            item.Attributes.Add(OptionGroupTag, optgroupLabel);
                        }
                        if (this.Page != null)
                        {
                            this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);
                        }

                        writer.Write('>');
                        HttpUtility.HtmlEncode(item.Text, writer);
                        writer.WriteEndTag(tag);
                        writer.WriteLine();
                        if (i == count - 1)
                        {
                            if (prevOptGroup != null)
                            {
                                writer.WriteEndTag(OptionGroupTag);
                            }
                        }
                    }
                }
            }
        }

        protected override object SaveViewState()
        {
            object[] state = new object[this.Items.Count + 1];
            object baseState = base.SaveViewState();
            state[0] = baseState;
            bool itemHasAttributes = false;

            for (int i = 0; i < this.Items.Count; i++)
            {
                if (this.Items[i].Attributes.Count > 0)
                {
                    itemHasAttributes = true;
                    object[] attributes = new object[this.Items[i].Attributes.Count * 2];
                    int k = 0;

                    foreach (string key in this.Items[i].Attributes.Keys)
                    {
                        attributes[k] = key;
                        k++;
                        attributes[k] = this.Items[i].Attributes[key];
                        k++;
                    }
                    state[i + 1] = attributes;
                }
            }

            if (itemHasAttributes)
                return state;
            return baseState;
        }

        protected override void LoadViewState(object savedState)
        {
            if (savedState == null)
                return;

            if (!(savedState.GetType().GetElementType() == null) &&
                (savedState.GetType().GetElementType().Equals(typeof(object))))
            {
                object[] state = (object[])savedState;
                base.LoadViewState(state[0]);

                for (int i = 1; i < state.Length; i++)
                {
                    if (state[i] != null)
                    {
                        object[] attributes = (object[])state[i];
                        for (int k = 0; k < attributes.Length; k += 2)
                        {
                            this.Items[i - 1].Attributes.Add
                                (attributes[k].ToString(), attributes[k + 1].ToString());
                        }
                    }
                }
            }
            else
            {
                base.LoadViewState(savedState);
            }
        }
    }
}

- 构建扩展类项目以生成DLL文件

如何使用扩展程序

- 将生成的DLL添加到WebForms项目中 - 在您需要DropDownList扩展名的页面中添加对您的程序集的引用(示例如下)。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyPage.aspx.cs" Inherits="MyWebProject.MyFolder.MyPage" %>
<%@ Register TagPrefix="Ext" Namespace="MyProjectName" Assembly="MyProjectName" %>

// <!DOCTYPE html> ... various other elements and controls ...

<Ext:ExtendedDropDownList ID="MyDropDownList" runat="server"
    AutoPostBack="true"
    OnSelectedIndexChanged="MyDropDownList_SelectedIndexChanged">
</Ext:ExtendedDropDownList>

代码背后

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        FeedDropDownList();
    }           
}

private void FeedDropDownList()
{
    var dao = new CarDAO();
    var cars = dao.GetCars();

    ListItem empty = new ListItem(string.Empty, "0");
    empty.Selected = true;
    MyDropDownList.Items.Add(empty);

    foreach (dynamic carBrands in from c in cars
                                 group c by c.Brand into cg
                                 select new { Brand = cg.Key, Cars = cg  })
    {
        foreach(Car c in carBrands.Cars)
        {
            ListItem item = new ListItem(c.Model, c.Id.ToString());
            item.Attributes.Add("optgroup", carBrands.Brand);
            MyDropDownList.Items.Add(item);
        }
    }
}

protected void Dropdownlist_SelectedIndexChanged(object sender, EventArgs e)
{
    var dropdown = sender as DropDownList;
    if (dropdown == null)
        return;

    var value = dropdown.SelectedValue;
}

车级

public class Car
{
    public int Id { get; set; }
    public string Model { get; set; }
    public string Brand { get; set; }
}

CarDAO课程

public class CarDAO
{
    public Car[] GetCars()
    {
        var cars = 
            new Car[] {
                new Car
                {
                    Id = 1,
                    Model = "718 Cayman",
                    Brand = "Porsche"
                },
                new Car
                {
                    Id = 2,
                    Model = "718 Boxster",
                    Brand = "Porsche"
                },
                new Car
                {
                    Id = 3,
                    Model = "718 GTS",
                    Brand = "Porsche"
                },
                new Car
                {
                    Id = 4,
                    Model = "911 Carrera",
                    Brand = "Porsche"
                },
                new Car
                {
                    Id = 5,
                    Model = "718 GTS",
                    Brand = "Porsche"
                },
                new Car
                {
                    Id = 6,
                    Model = "812 Superfast",
                    Brand = "Ferrari"
                },
                new Car
                {
                    Id = 7,
                    Model = "GTC4 Lusso",
                    Brand = "Ferrari"
                },
                new Car
                {
                    Id = 8,
                    Model = "488 GTB",
                    Brand = "Ferrari"
                },
                new Car
                {
                    Id = 9,
                    Model = "488 Spider",
                    Brand = "Ferrari"
                },
                new Car
                {
                    Id = 10,
                    Model = "LaFerrari Aperta",
                    Brand = "Ferrari"
                }
            };
        return cars;
    }
}

enter image description here

答案 1 :(得分:-4)

Xml和html非常不同。不要混淆。使用xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            XElement select = new XElement("select");

            foreach (Car car in Car.cars)
            {
                XElement newCar = new XElement("optgroup", new XAttribute("label", car.country));
                select.Add(newCar);
                foreach (string name in car.names)
                {
                    newCar.Add(new XElement("option", new object[] {
                       new XAttribute("value", name),
                       name
                    }));
                }
            }
        }
    }
    public class Car
    {
        public static List<Car> cars = new List<Car>() {
            new Car() {
                country = "Swedish Cars",
                names = new List<string> {"Volvo", "saab"}
            },
            new Car() {
                country = "German Cars",
                names = new List<string> {"mercedes", "audi"}
            }
        };


        public string country { get; set; }
        public List<string> names { get; set; }
    }
}