Using databinding to populate a HtmlSelect with optgroup elements in asp.net
I am using asp.net and have a HtmlSelect
element on my page (with runat="server"
). Normally I will just set the DataSource
to some loaded data and Dat开发者_Go百科aBind
. However in this case the data has one level of hierarchy and I want to represent this in the HTML with an optgroup
. Google hasn't come up with any joy - is this even possible?
I've had a similar problem to solve and this is how I did it. Before I continue I did find all sorts of re-fracturing methods for lists, which probably do work. However, I did not think this the best route to go for my solution. Here's what I did:
I also needed to know which option a user selected in the drop down list but found that you can't build drop down list with option groups in ASP.net. So to do this I just built a simple <select>
with <optgroup>
's and <option>
's in each group. Then I placed a <div>
with a hidden textbox, which had the runat="server"
set. I set the "onchange"
event, on the select, to change the text value of the hidden textbox to whatever the value the option was, which was selected by the user, using javascript. Then, when the post back occurs, the code behind had access to the value the user selected, via the hidden textbox's runat="server"
. Problem solved! The code looks something like this:
Code in the HTML (aspx):
<div id="selectDiv">
<select id="selectItems" onchange="document.getElementById('hiddenselectDiv').getElementsByTagName('input')[0].value = this.options[this.selectedIndex].value;">
<optgroup label="Johannesburg">
<option value="Wilropark">Wilropark</option>
<option value="Bryanpark">Bryanpark</option>
<option value="Hurlingham">Hurlingham</option>
<option value="Midrand ">Midrand </option>
<option value="Glenvista">Glenvista</option>
<option value="Sunninghill">Sunninghill</option>
<option value="Edenvale ">Edenvale </option>
<option value="Parkhurst">Parkhurst</option>
</optgroup>
<optgroup label="Cape Town">
<option value="Tokai">Tokai</option>
<option value="Durbanville">Durbanville</option>
</optgroup>
<optgroup label="Durban">
<option value="Musgrave">Musgrave</option>
</optgroup>
<optgroup label="Pretoria">
<option value="Hatfield">Hatfield</option>
</optgroup>
</select>
</div>
<div id="hiddenSelectDiv">
<!--
Note: You probably want to set the hidden value to the first item you have seleced when you build the <select> object.
-->
<input type="hidden" id="selectedItem" value="Wilropark">
</div>
In the Code behind (C#):
if (!string.IsNullOrEmpty(selectedItem.Value))
{
//validation or whatever you want....
}
I've been looking around for the same thing, and it doesn't look like ASP supports this natively. One Google search found someone recommending a library at http://www.codeplex.com/SharpPieces, but I've never used it and I don't know how good it is. Other people talk about writing your own renderer for optgroup support.
精彩评论