开发者

ASP.NET: Dynamically creating controls

I have the following scenario:

My page has a dropdown list that allows user to choose a 开发者_Python百科category. For each category, there is a set of attributes, whose values should be fetched from the user. The number of attributes are different for each category. Depending on the category the user chooses, a set of dropdown lists should be created corresponding to the attributes and filled with corresponding attribute values.

ASP.NET: Dynamically creating controls

Since it is required that the page should not reload, I plan to fetch the data (from SQL Server 2008) using AJAX (?). I'm new to ASP.NET and have not used AJAX though I'm comfortable with C#. Need advice on how to proceed.

EDIT: Is this useful if I need to dynamically generate combo boxes?


You can use UpdatePanel or PageMethods

in both cases and in any case, I would say, you do need to know JavaScript when you want to use AJAX and make dynamic web applications. It take some time but it pays off don't worry.

you can search here in SO about PageMethod, for example see this one:

Regarding PageMethod in asp.net


You could use the following approach (if you do not feel comfortable building a more complex UI with javascript).

It works by dynamically creating the attribute DropDownLists when the page loads (you would implement it based on the result of a DB query) and hiding each one, ready for display later on.

Upon the selection of a category the correct DropDownLists would then be made visible (again a query here could determine which attribute DropDownLists become visible).

Obviously it will require some modifications to probably generate a Panel which contains each DropDownList and a Label control, instead of just creating a number of DropDownLists.

You would then show/hide the Panel instead of the DropDownList, but hopefully it points you in the right direction.

Hope this helps.

Markup

<style type="text/css">
    select
    {
        display:block;
        margin-top:10px;
    }
</style>

....

<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
    <ContentTemplate>

        <!-- Category selection -->
        <asp:DropDownList ID="categoryDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="categoryDropDownList_SelectedIndexChanged">
            <asp:ListItem Text="Please select a category" Value="0"></asp:ListItem>
        </asp:DropDownList>

        <br />

        <!-- Used to store the drop downs -->
        <asp:Panel ID="dropDownContainer" runat="server"></asp:Panel>

    </ContentTemplate>
</asp:UpdatePanel>

Code

protected void Page_Load(object sender, EventArgs e)
{
    LoadDropDownLists();
}

private void LoadDropDownLists()
{
    //Dummy data, you would pull your categories/attributes from whichever datasource
    //you are using
    var categories = new[]{
        new { Name = "Category 1", Id = 1, Attributes = new string[]{"GA", "FA", "RA"} },
        new { Name = "Category 2", Id = 2, Attributes = new string[]{"GA", "NA"} }
    };

    //Loop through the categories, load the dropdown
    foreach (var category in categories)
    {
        if (!IsPostBack)
            categoryDropDownList.Items.Add(new ListItem(category.Name, category.Id.ToString()));

        //For each attribute create a drop down and populate with data as required
        foreach (var attribute in category.Attributes)
        {
            string dropDownListId = FormatDropDownListId(attribute);
            if (!DropDownListExists(dropDownListId))
            {
                DropDownList dropDownList = new DropDownList();
                dropDownList.ID = dropDownListId;
                dropDownList.Visible = false;

                dropDownList.Items.Add(new ListItem(attribute));

                dropDownContainer.Controls.Add(dropDownList);
            }
        }
    }
}

private bool DropDownListExists(string id)
{
    DropDownList dropDownList = (DropDownList)dropDownContainer.FindControl(id);
    return dropDownList != null;
}

protected void categoryDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
    //Reset all visible dropdowns
    HideAllDropDownLists();

    //Get the selected category
    string selectedItem = categoryDropDownList.SelectedItem.Value;
    switch (selectedItem)
    {
        case "1":
            {
                //Here you would connect to db and pull correct attributes
                //then set the visible dropdowns as required
                SetDropDownVisibility(FormatDropDownListId("GA"));
                SetDropDownVisibility(FormatDropDownListId("FA"));
                SetDropDownVisibility(FormatDropDownListId("RA"));
            } break;
        case "2":
            {
                SetDropDownVisibility(FormatDropDownListId("GA"));
                SetDropDownVisibility(FormatDropDownListId("NA"));
            } break;
    }
}

private void SetDropDownVisibility(string id)
{
    DropDownList dropDownList = (DropDownList)dropDownContainer.FindControl(id);
    if(dropDownList != null)
        dropDownList.Visible = true;
}

private void HideAllDropDownLists()
{
    foreach (Control control in dropDownContainer.Controls)
    {
        control.Visible = false;
    }
}

private string FormatDropDownListId(string id)
{
    return string.Format("dropDown{0}", id);
}


If you're using ASP.NET webforms then I don't believe you need to use AJAX or JavaScript.

I would do the following

  1. Set autopostback = true on your combobox
  2. Add an event handler for the OnChanged event of the combobox
  3. Inside the event handler, apply rules at to load / generate / populate child comboboxes
  4. Add those combo boxes to the form

You can either hide the comboboxes (as I see in @jdavies answer), or start without any and dynamically create & add them to the form.

This question deals with the same issue:

DropDownList and Update Panel

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜